Merge pull request #818 from sandrine-bailleux-arm/sb/strnlen

Add strnlen() to local C library
diff --git a/Makefile b/Makefile
index adfdba6..e9a0784 100644
--- a/Makefile
+++ b/Makefile
@@ -66,7 +66,7 @@
 					include/lib,			\
 					$(wildcard include/*)))
 LIB_DIRS_TO_CHECK	:=	$(sort $(filter-out			\
-					lib/libfdt			\
+					lib/libfdt%			\
 					lib/stdlib,			\
 					$(wildcard lib/*)))
 ROOT_DIRS_TO_CHECK	:=	$(sort $(filter-out			\
@@ -568,7 +568,7 @@
 checkcodebase:		locate-checkpatch
 	@echo "  CHECKING STYLE"
 	@if test -d .git ; then						\
-		git ls-files | grep -E -v libfdt\|stdlib\|docs\|\.md |	\
+		git ls-files | grep -E -v 'libfdt|stdlib|docs|\.md' |	\
 		while read GIT_FILE ;					\
 		do ${CHECKPATCH} ${CHECKCODE_ARGS} -f $$GIT_FILE ;	\
 		done ;							\
diff --git a/drivers/arm/ccn/ccn.c b/drivers/arm/ccn/ccn.c
index 060acdd..d739c6b 100644
--- a/drivers/arm/ccn/ccn.c
+++ b/drivers/arm/ccn/ccn.c
@@ -38,7 +38,7 @@
 #include "ccn_private.h"
 
 static const ccn_desc_t *ccn_plat_desc;
-#if IMAGE_BL31
+#ifdef IMAGE_BL31
 DEFINE_BAKERY_LOCK(ccn_lock);
 #endif
 
@@ -285,7 +285,7 @@
 	assert(ccn_plat_desc);
 	assert(ccn_plat_desc->periphbase);
 
-#if IMAGE_BL31
+#ifdef IMAGE_BL31
 	bakery_lock_get(&ccn_lock);
 #endif
 	start_region_id = region_id;
@@ -305,7 +305,7 @@
 						   rn_id_map);
 	}
 
-#if IMAGE_BL31
+#ifdef IMAGE_BL31
 	bakery_lock_release(&ccn_lock);
 #endif
 }
diff --git a/drivers/auth/mbedtls/mbedtls_x509_parser.c b/drivers/auth/mbedtls/mbedtls_x509_parser.c
index 1a6a9a7..73da9d1 100644
--- a/drivers/auth/mbedtls/mbedtls_x509_parser.c
+++ b/drivers/auth/mbedtls/mbedtls_x509_parser.c
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 2015, ARM Limited and Contributors. All rights reserved.
+ * Copyright (c) 2015-2017, ARM Limited and Contributors. All rights reserved.
  *
  * Redistribution and use in source and binary forms, with or without
  * modification, are permitted provided that the following conditions are met:
@@ -36,6 +36,7 @@
  * extensions field, such as an image hash or a public key.
  */
 
+#include <arch_helpers.h>
 #include <assert.h>
 #include <img_parser_mod.h>
 #include <mbedtls_common.h>
@@ -64,6 +65,26 @@
 static mbedtls_asn1_buf signature;
 
 /*
+ * Clear all static temporary variables.
+ */
+static void clear_temp_vars(void)
+{
+#define ZERO_AND_CLEAN(x)					\
+	do {							\
+		memset(&x, 0, sizeof(x));			\
+		clean_dcache_range((uintptr_t)&x, sizeof(x));	\
+	} while (0);
+
+	ZERO_AND_CLEAN(tbs)
+	ZERO_AND_CLEAN(v3_ext);
+	ZERO_AND_CLEAN(pk);
+	ZERO_AND_CLEAN(sig_alg);
+	ZERO_AND_CLEAN(signature);
+
+#undef ZERO_AND_CLEAN
+}
+
+/*
  * Get X509v3 extension
  *
  * Global variable 'v3_ext' must point to the extensions region
@@ -134,7 +155,12 @@
 
 /*
  * Check the integrity of the certificate ASN.1 structure.
+ *
  * Extract the relevant data that will be used later during authentication.
+ *
+ * This function doesn't clear the static variables located on the top of this
+ * file in case of an error. It is only called from check_integrity(), which
+ * performs the cleanup if necessary.
  */
 static int cert_parse(void *img, unsigned int img_len)
 {
@@ -398,9 +424,18 @@
 	mbedtls_init();
 }
 
+/*
+ * Wrapper for cert_parse() that clears the static variables used by it in case
+ * of an error.
+ */
 static int check_integrity(void *img, unsigned int img_len)
 {
-	return cert_parse(img, img_len);
+	int rc = cert_parse(img, img_len);
+
+	if (rc != IMG_PARSER_OK)
+		clear_temp_vars();
+
+	return rc;
 }
 
 /*
diff --git a/drivers/synopsys/emmc/dw_mmc.c b/drivers/synopsys/emmc/dw_mmc.c
new file mode 100644
index 0000000..5b15683
--- /dev/null
+++ b/drivers/synopsys/emmc/dw_mmc.c
@@ -0,0 +1,424 @@
+/*
+ * Copyright (c) 2016-2017, ARM Limited and Contributors. All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions are met:
+ *
+ * Redistributions of source code must retain the above copyright notice, this
+ * list of conditions and the following disclaimer.
+ *
+ * Redistributions in binary form must reproduce the above copyright notice,
+ * this list of conditions and the following disclaimer in the documentation
+ * and/or other materials provided with the distribution.
+ *
+ * Neither the name of ARM nor the names of its contributors may be used
+ * to endorse or promote products derived from this software without specific
+ * prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
+ * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+ * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
+ * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
+ * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
+ * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
+ * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
+ * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
+ * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
+ * POSSIBILITY OF SUCH DAMAGE.
+ */
+
+#include <arch.h>
+#include <arch_helpers.h>
+#include <assert.h>
+#include <debug.h>
+#include <delay_timer.h>
+#include <dw_mmc.h>
+#include <emmc.h>
+#include <errno.h>
+#include <mmio.h>
+#include <string.h>
+
+#define DWMMC_CTRL			(0x00)
+#define CTRL_IDMAC_EN			(1 << 25)
+#define CTRL_DMA_EN			(1 << 5)
+#define CTRL_INT_EN			(1 << 4)
+#define CTRL_DMA_RESET			(1 << 2)
+#define CTRL_FIFO_RESET			(1 << 1)
+#define CTRL_RESET			(1 << 0)
+#define CTRL_RESET_ALL			(CTRL_DMA_RESET | CTRL_FIFO_RESET | \
+					 CTRL_RESET)
+
+#define DWMMC_PWREN			(0x04)
+#define DWMMC_CLKDIV			(0x08)
+#define DWMMC_CLKSRC			(0x0c)
+#define DWMMC_CLKENA			(0x10)
+#define DWMMC_TMOUT			(0x14)
+#define DWMMC_CTYPE			(0x18)
+#define CTYPE_8BIT			(1 << 16)
+#define CTYPE_4BIT			(1)
+#define CTYPE_1BIT			(0)
+
+#define DWMMC_BLKSIZ			(0x1c)
+#define DWMMC_BYTCNT			(0x20)
+#define DWMMC_INTMASK			(0x24)
+#define INT_EBE				(1 << 15)
+#define INT_SBE				(1 << 13)
+#define INT_HLE				(1 << 12)
+#define INT_FRUN			(1 << 11)
+#define INT_DRT				(1 << 9)
+#define INT_RTO				(1 << 8)
+#define INT_DCRC			(1 << 7)
+#define INT_RCRC			(1 << 6)
+#define INT_RXDR			(1 << 5)
+#define INT_TXDR			(1 << 4)
+#define INT_DTO				(1 << 3)
+#define INT_CMD_DONE			(1 << 2)
+#define INT_RE				(1 << 1)
+
+#define DWMMC_CMDARG			(0x28)
+#define DWMMC_CMD			(0x2c)
+#define CMD_START			(1 << 31)
+#define CMD_USE_HOLD_REG		(1 << 29)	/* 0 if SDR50/100 */
+#define CMD_UPDATE_CLK_ONLY		(1 << 21)
+#define CMD_SEND_INIT			(1 << 15)
+#define CMD_STOP_ABORT_CMD		(1 << 14)
+#define CMD_WAIT_PRVDATA_COMPLETE	(1 << 13)
+#define CMD_WRITE			(1 << 10)
+#define CMD_DATA_TRANS_EXPECT		(1 << 9)
+#define CMD_CHECK_RESP_CRC		(1 << 8)
+#define CMD_RESP_LEN			(1 << 7)
+#define CMD_RESP_EXPECT			(1 << 6)
+#define CMD(x)				(x & 0x3f)
+
+#define DWMMC_RESP0			(0x30)
+#define DWMMC_RESP1			(0x34)
+#define DWMMC_RESP2			(0x38)
+#define DWMMC_RESP3			(0x3c)
+#define DWMMC_RINTSTS			(0x44)
+#define DWMMC_STATUS			(0x48)
+#define STATUS_DATA_BUSY		(1 << 9)
+
+#define DWMMC_FIFOTH			(0x4c)
+#define FIFOTH_TWMARK(x)		(x & 0xfff)
+#define FIFOTH_RWMARK(x)		((x & 0x1ff) << 16)
+#define FIFOTH_DMA_BURST_SIZE(x)	((x & 0x7) << 28)
+
+#define DWMMC_DEBNCE			(0x64)
+#define DWMMC_BMOD			(0x80)
+#define BMOD_ENABLE			(1 << 7)
+#define BMOD_FB				(1 << 1)
+#define BMOD_SWRESET			(1 << 0)
+
+#define DWMMC_DBADDR			(0x88)
+#define DWMMC_IDSTS			(0x8c)
+#define DWMMC_IDINTEN			(0x90)
+#define DWMMC_CARDTHRCTL		(0x100)
+#define CARDTHRCTL_RD_THR(x)		((x & 0xfff) << 16)
+#define CARDTHRCTL_RD_THR_EN		(1 << 0)
+
+#define IDMAC_DES0_DIC			(1 << 1)
+#define IDMAC_DES0_LD			(1 << 2)
+#define IDMAC_DES0_FS			(1 << 3)
+#define IDMAC_DES0_CH			(1 << 4)
+#define IDMAC_DES0_ER			(1 << 5)
+#define IDMAC_DES0_CES			(1 << 30)
+#define IDMAC_DES0_OWN			(1 << 31)
+#define IDMAC_DES1_BS1(x)		((x) & 0x1fff)
+#define IDMAC_DES2_BS2(x)		(((x) & 0x1fff) << 13)
+
+#define DWMMC_DMA_MAX_BUFFER_SIZE	(512 * 8)
+
+#define DWMMC_8BIT_MODE			(1 << 6)
+
+#define TIMEOUT				100000
+
+struct dw_idmac_desc {
+	unsigned int	des0;
+	unsigned int	des1;
+	unsigned int	des2;
+	unsigned int	des3;
+};
+
+static void dw_init(void);
+static int dw_send_cmd(emmc_cmd_t *cmd);
+static int dw_set_ios(int clk, int width);
+static int dw_prepare(int lba, uintptr_t buf, size_t size);
+static int dw_read(int lba, uintptr_t buf, size_t size);
+static int dw_write(int lba, uintptr_t buf, size_t size);
+
+static const emmc_ops_t dw_mmc_ops = {
+	.init		= dw_init,
+	.send_cmd	= dw_send_cmd,
+	.set_ios	= dw_set_ios,
+	.prepare	= dw_prepare,
+	.read		= dw_read,
+	.write		= dw_write,
+};
+
+static dw_mmc_params_t dw_params;
+
+static void dw_update_clk(void)
+{
+	unsigned int data;
+
+	mmio_write_32(dw_params.reg_base + DWMMC_CMD,
+		      CMD_WAIT_PRVDATA_COMPLETE | CMD_UPDATE_CLK_ONLY |
+		      CMD_START);
+	while (1) {
+		data = mmio_read_32(dw_params.reg_base + DWMMC_CMD);
+		if ((data & CMD_START) == 0)
+			break;
+		data = mmio_read_32(dw_params.reg_base + DWMMC_RINTSTS);
+		assert(data & INT_HLE);
+	}
+}
+
+static void dw_set_clk(int clk)
+{
+	unsigned int data;
+	int div;
+
+	assert(clk > 0);
+
+	for (div = 1; div < 256; div++) {
+		if ((dw_params.clk_rate / (2 * div)) <= clk) {
+			break;
+		}
+	}
+	assert(div < 256);
+
+	/* wait until controller is idle */
+	do {
+		data = mmio_read_32(dw_params.reg_base + DWMMC_STATUS);
+	} while (data & STATUS_DATA_BUSY);
+
+	/* disable clock before change clock rate */
+	mmio_write_32(dw_params.reg_base + DWMMC_CLKENA, 0);
+	dw_update_clk();
+
+	mmio_write_32(dw_params.reg_base + DWMMC_CLKDIV, div);
+	dw_update_clk();
+
+	/* enable clock */
+	mmio_write_32(dw_params.reg_base + DWMMC_CLKENA, 1);
+	mmio_write_32(dw_params.reg_base + DWMMC_CLKSRC, 0);
+	dw_update_clk();
+}
+
+static void dw_init(void)
+{
+	unsigned int data;
+	uintptr_t base;
+
+	assert((dw_params.reg_base & EMMC_BLOCK_MASK) == 0);
+
+	base = dw_params.reg_base;
+	mmio_write_32(base + DWMMC_PWREN, 1);
+	mmio_write_32(base + DWMMC_CTRL, CTRL_RESET_ALL);
+	do {
+		data = mmio_read_32(base + DWMMC_CTRL);
+	} while (data);
+
+	/* enable DMA in CTRL */
+	data = CTRL_INT_EN | CTRL_DMA_EN | CTRL_IDMAC_EN;
+	mmio_write_32(base + DWMMC_CTRL, data);
+	mmio_write_32(base + DWMMC_RINTSTS, ~0);
+	mmio_write_32(base + DWMMC_INTMASK, 0);
+	mmio_write_32(base + DWMMC_TMOUT, ~0);
+	mmio_write_32(base + DWMMC_IDINTEN, ~0);
+	mmio_write_32(base + DWMMC_BLKSIZ, EMMC_BLOCK_SIZE);
+	mmio_write_32(base + DWMMC_BYTCNT, 256 * 1024);
+	mmio_write_32(base + DWMMC_DEBNCE, 0x00ffffff);
+	mmio_write_32(base + DWMMC_BMOD, BMOD_SWRESET);
+	do {
+		data = mmio_read_32(base + DWMMC_BMOD);
+	} while (data & BMOD_SWRESET);
+	/* enable DMA in BMOD */
+	data |= BMOD_ENABLE | BMOD_FB;
+	mmio_write_32(base + DWMMC_BMOD, data);
+
+	udelay(100);
+	dw_set_clk(EMMC_BOOT_CLK_RATE);
+	udelay(100);
+}
+
+static int dw_send_cmd(emmc_cmd_t *cmd)
+{
+	unsigned int op, data, err_mask;
+	uintptr_t base;
+	int timeout;
+
+	assert(cmd);
+
+	base = dw_params.reg_base;
+
+	switch (cmd->cmd_idx) {
+	case EMMC_CMD0:
+		op = CMD_SEND_INIT;
+		break;
+	case EMMC_CMD12:
+		op = CMD_STOP_ABORT_CMD;
+		break;
+	case EMMC_CMD13:
+		op = CMD_WAIT_PRVDATA_COMPLETE;
+		break;
+	case EMMC_CMD8:
+	case EMMC_CMD17:
+	case EMMC_CMD18:
+		op = CMD_DATA_TRANS_EXPECT | CMD_WAIT_PRVDATA_COMPLETE;
+		break;
+	case EMMC_CMD24:
+	case EMMC_CMD25:
+		op = CMD_WRITE | CMD_DATA_TRANS_EXPECT |
+		     CMD_WAIT_PRVDATA_COMPLETE;
+		break;
+	default:
+		op = 0;
+		break;
+	}
+	op |= CMD_USE_HOLD_REG | CMD_START;
+	switch (cmd->resp_type) {
+	case 0:
+		break;
+	case EMMC_RESPONSE_R2:
+		op |= CMD_RESP_EXPECT | CMD_CHECK_RESP_CRC |
+		      CMD_RESP_LEN;
+		break;
+	case EMMC_RESPONSE_R3:
+		op |= CMD_RESP_EXPECT;
+		break;
+	default:
+		op |= CMD_RESP_EXPECT | CMD_CHECK_RESP_CRC;
+		break;
+	}
+	timeout = TIMEOUT;
+	do {
+		data = mmio_read_32(base + DWMMC_STATUS);
+		if (--timeout <= 0)
+			panic();
+	} while (data & STATUS_DATA_BUSY);
+
+	mmio_write_32(base + DWMMC_RINTSTS, ~0);
+	mmio_write_32(base + DWMMC_CMDARG, cmd->cmd_arg);
+	mmio_write_32(base + DWMMC_CMD, op | cmd->cmd_idx);
+
+	err_mask = INT_EBE | INT_HLE | INT_RTO | INT_RCRC | INT_RE |
+		   INT_DCRC | INT_DRT | INT_SBE;
+	timeout = TIMEOUT;
+	do {
+		udelay(500);
+		data = mmio_read_32(base + DWMMC_RINTSTS);
+
+		if (data & err_mask)
+			return -EIO;
+		if (data & INT_DTO)
+			break;
+		if (--timeout == 0) {
+			ERROR("%s, RINTSTS:0x%x\n", __func__, data);
+			panic();
+		}
+	} while (!(data & INT_CMD_DONE));
+
+	if (op & CMD_RESP_EXPECT) {
+		cmd->resp_data[0] = mmio_read_32(base + DWMMC_RESP0);
+		if (op & CMD_RESP_LEN) {
+			cmd->resp_data[1] = mmio_read_32(base + DWMMC_RESP1);
+			cmd->resp_data[2] = mmio_read_32(base + DWMMC_RESP2);
+			cmd->resp_data[3] = mmio_read_32(base + DWMMC_RESP3);
+		}
+	}
+	return 0;
+}
+
+static int dw_set_ios(int clk, int width)
+{
+	switch (width) {
+	case EMMC_BUS_WIDTH_1:
+		mmio_write_32(dw_params.reg_base + DWMMC_CTYPE, CTYPE_1BIT);
+		break;
+	case EMMC_BUS_WIDTH_4:
+		mmio_write_32(dw_params.reg_base + DWMMC_CTYPE, CTYPE_4BIT);
+		break;
+	case EMMC_BUS_WIDTH_8:
+		mmio_write_32(dw_params.reg_base + DWMMC_CTYPE, CTYPE_8BIT);
+		break;
+	default:
+		assert(0);
+	}
+	dw_set_clk(clk);
+	return 0;
+}
+
+static int dw_prepare(int lba, uintptr_t buf, size_t size)
+{
+	struct dw_idmac_desc *desc;
+	int desc_cnt, i, last;
+	uintptr_t base;
+
+	assert(((buf & EMMC_BLOCK_MASK) == 0) &&
+	       ((size % EMMC_BLOCK_SIZE) == 0) &&
+	       (dw_params.desc_size > 0) &&
+	       ((dw_params.reg_base & EMMC_BLOCK_MASK) == 0) &&
+	       ((dw_params.desc_base & EMMC_BLOCK_MASK) == 0) &&
+	       ((dw_params.desc_size & EMMC_BLOCK_MASK) == 0));
+
+	desc_cnt = (size + DWMMC_DMA_MAX_BUFFER_SIZE - 1) /
+		   DWMMC_DMA_MAX_BUFFER_SIZE;
+	assert(desc_cnt * sizeof(struct dw_idmac_desc) < dw_params.desc_size);
+
+	base = dw_params.reg_base;
+	desc = (struct dw_idmac_desc *)dw_params.desc_base;
+	mmio_write_32(base + DWMMC_BYTCNT, size);
+	mmio_write_32(base + DWMMC_RINTSTS, ~0);
+	for (i = 0; i < desc_cnt; i++) {
+		desc[i].des0 = IDMAC_DES0_OWN | IDMAC_DES0_CH | IDMAC_DES0_DIC;
+		desc[i].des1 = IDMAC_DES1_BS1(DWMMC_DMA_MAX_BUFFER_SIZE);
+		desc[i].des2 = buf + DWMMC_DMA_MAX_BUFFER_SIZE * i;
+		desc[i].des3 = dw_params.desc_base +
+			       (sizeof(struct dw_idmac_desc)) * (i + 1);
+	}
+	/* first descriptor */
+	desc->des0 |= IDMAC_DES0_FS;
+	/* last descriptor */
+	last = desc_cnt - 1;
+	(desc + last)->des0 |= IDMAC_DES0_LD;
+	(desc + last)->des0 &= ~(IDMAC_DES0_DIC | IDMAC_DES0_CH);
+	(desc + last)->des1 = IDMAC_DES1_BS1(size - (last *
+				  DWMMC_DMA_MAX_BUFFER_SIZE));
+	/* set next descriptor address as 0 */
+	(desc + last)->des3 = 0;
+
+	mmio_write_32(base + DWMMC_DBADDR, dw_params.desc_base);
+	clean_dcache_range(dw_params.desc_base,
+			   desc_cnt * DWMMC_DMA_MAX_BUFFER_SIZE);
+
+	return 0;
+}
+
+static int dw_read(int lba, uintptr_t buf, size_t size)
+{
+	return 0;
+}
+
+static int dw_write(int lba, uintptr_t buf, size_t size)
+{
+	return 0;
+}
+
+void dw_mmc_init(dw_mmc_params_t *params)
+{
+	assert((params != 0) &&
+	       ((params->reg_base & EMMC_BLOCK_MASK) == 0) &&
+	       ((params->desc_base & EMMC_BLOCK_MASK) == 0) &&
+	       ((params->desc_size & EMMC_BLOCK_MASK) == 0) &&
+	       (params->desc_size > 0) &&
+	       (params->clk_rate > 0) &&
+	       ((params->bus_width == EMMC_BUS_WIDTH_1) ||
+		(params->bus_width == EMMC_BUS_WIDTH_4) ||
+		(params->bus_width == EMMC_BUS_WIDTH_8)));
+
+	memcpy(&dw_params, params, sizeof(dw_mmc_params_t));
+	emmc_init(&dw_mmc_ops, params->clk_rate, params->bus_width,
+		  params->flags);
+}
diff --git a/include/common/aarch32/el3_common_macros.S b/include/common/aarch32/el3_common_macros.S
index dcb4edd..463a080 100644
--- a/include/common/aarch32/el3_common_macros.S
+++ b/include/common/aarch32/el3_common_macros.S
@@ -228,7 +228,7 @@
 	 * ---------------------------------------------------------------------
 	 */
 	.if \_init_c_runtime
-#if IMAGE_BL32
+#ifdef IMAGE_BL32
 		/* -----------------------------------------------------------------
 		 * Invalidate the RW memory used by the BL32 (SP_MIN) image. This
 		 * includes the data and NOBITS sections. This is done to
@@ -253,7 +253,7 @@
 		bl	zeromem
 #endif
 
-#if IMAGE_BL1
+#ifdef IMAGE_BL1
 		/* -----------------------------------------------------
 		 * Copy data from ROM to RAM.
 		 * -----------------------------------------------------
diff --git a/include/common/aarch64/el3_common_macros.S b/include/common/aarch64/el3_common_macros.S
index a418911..cbfa6ee 100644
--- a/include/common/aarch64/el3_common_macros.S
+++ b/include/common/aarch64/el3_common_macros.S
@@ -49,7 +49,7 @@
 	msr	sctlr_el3, x0
 	isb
 
-#if IMAGE_BL31
+#ifdef IMAGE_BL31
 	/* ---------------------------------------------------------------------
 	 * Initialise the per-cpu cache pointer to the CPU.
 	 * This is done early to enable crash reporting to have access to crash
@@ -235,7 +235,7 @@
 	 * ---------------------------------------------------------------------
 	 */
 	.if \_init_c_runtime
-#if IMAGE_BL31
+#ifdef IMAGE_BL31
 		/* -------------------------------------------------------------
 		 * Invalidate the RW memory used by the BL31 image. This
 		 * includes the data and NOBITS sections. This is done to
@@ -260,7 +260,7 @@
 		bl	zeromem16
 #endif
 
-#if IMAGE_BL1
+#ifdef IMAGE_BL1
 		ldr	x0, =__DATA_RAM_START__
 		ldr	x1, =__DATA_ROM_START__
 		ldr	x2, =__DATA_SIZE__
diff --git a/include/common/bl_common.h b/include/common/bl_common.h
index 5076dfd..66c20fc 100644
--- a/include/common/bl_common.h
+++ b/include/common/bl_common.h
@@ -170,13 +170,13 @@
 extern uintptr_t __RO_END__;
 #endif
 
-#if IMAGE_BL2
+#if defined(IMAGE_BL2)
 extern uintptr_t __BL2_END__;
-#elif IMAGE_BL2U
+#elif defined(IMAGE_BL2U)
 extern uintptr_t __BL2U_END__;
-#elif IMAGE_BL31
+#elif defined(IMAGE_BL31)
 extern uintptr_t __BL31_END__;
-#elif IMAGE_BL32
+#elif defined(IMAGE_BL32)
 extern uintptr_t __BL32_END__;
 #endif /* IMAGE_BLX */
 
diff --git a/include/drivers/synopsys/dw_mmc.h b/include/drivers/synopsys/dw_mmc.h
new file mode 100644
index 0000000..22192f8
--- /dev/null
+++ b/include/drivers/synopsys/dw_mmc.h
@@ -0,0 +1,45 @@
+/*
+ * Copyright (c) 2016-2017, ARM Limited and Contributors. All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions are met:
+ *
+ * Redistributions of source code must retain the above copyright notice, this
+ * list of conditions and the following disclaimer.
+ *
+ * Redistributions in binary form must reproduce the above copyright notice,
+ * this list of conditions and the following disclaimer in the documentation
+ * and/or other materials provided with the distribution.
+ *
+ * Neither the name of ARM nor the names of its contributors may be used
+ * to endorse or promote products derived from this software without specific
+ * prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
+ * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+ * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
+ * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
+ * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
+ * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
+ * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
+ * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
+ * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
+ * POSSIBILITY OF SUCH DAMAGE.
+ */
+
+#ifndef __DW_MMC_H__
+#define __DW_MMC_H__
+
+typedef struct dw_mmc_params {
+	uintptr_t	reg_base;
+	uintptr_t	desc_base;
+	size_t		desc_size;
+	int		clk_rate;
+	int		bus_width;
+	unsigned int	flags;
+} dw_mmc_params_t;
+
+void dw_mmc_init(dw_mmc_params_t *params);
+
+#endif	/* __DW_MMC_H__ */
diff --git a/include/lib/aarch32/arch_helpers.h b/include/lib/aarch32/arch_helpers.h
index 7955d62..3a82a7b 100644
--- a/include/lib/aarch32/arch_helpers.h
+++ b/include/lib/aarch32/arch_helpers.h
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 2016, ARM Limited and Contributors. All rights reserved.
+ * Copyright (c) 2016-2017, ARM Limited and Contributors. All rights reserved.
  *
  * Redistribution and use in source and binary forms, with or without
  * modification, are permitted provided that the following conditions are met:
@@ -33,7 +33,7 @@
 
 #include <arch.h>	/* for additional register definitions */
 #include <stdint.h>
-#include <types.h>
+#include <sys/types.h>
 
 /**********************************************************************
  * Macros which create inline functions to read or write CPU system
@@ -187,6 +187,9 @@
 void clean_dcache_range(uintptr_t addr, size_t size);
 void inv_dcache_range(uintptr_t addr, size_t size);
 
+void dcsw_op_louis(u_register_t op_type);
+void dcsw_op_all(u_register_t op_type);
+
 void disable_mmu_secure(void);
 void disable_mmu_icache_secure(void);
 
diff --git a/include/lib/aarch64/arch_helpers.h b/include/lib/aarch64/arch_helpers.h
index aa26203..d70c9ae 100644
--- a/include/lib/aarch64/arch_helpers.h
+++ b/include/lib/aarch64/arch_helpers.h
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 2013-2015, ARM Limited and Contributors. All rights reserved.
+ * Copyright (c) 2013-2017, ARM Limited and Contributors. All rights reserved.
  *
  * Redistribution and use in source and binary forms, with or without
  * modification, are permitted provided that the following conditions are met:
@@ -34,6 +34,7 @@
 #include <arch.h>	/* for additional register definitions */
 #include <cdefs.h>	/* For __dead2 */
 #include <stdint.h>
+#include <sys/types.h>
 
 /**********************************************************************
  * Macros which create inline functions to read or write CPU system
@@ -143,11 +144,12 @@
 DEFINE_SYSOP_TYPE_PARAM_FUNC(at, s12e0r)
 DEFINE_SYSOP_TYPE_PARAM_FUNC(at, s12e0w)
 
-void flush_dcache_range(uint64_t, uint64_t);
-void clean_dcache_range(uint64_t, uint64_t);
-void inv_dcache_range(uint64_t, uint64_t);
-void dcsw_op_louis(uint32_t);
-void dcsw_op_all(uint32_t);
+void flush_dcache_range(uintptr_t addr, size_t size);
+void clean_dcache_range(uintptr_t addr, size_t size);
+void inv_dcache_range(uintptr_t addr, size_t size);
+
+void dcsw_op_louis(u_register_t op_type);
+void dcsw_op_all(u_register_t op_type);
 
 void disable_mmu_el3(void);
 void disable_mmu_icache_el3(void);
diff --git a/include/lib/cpus/aarch32/cpu_macros.S b/include/lib/cpus/aarch32/cpu_macros.S
index 17dd258..64df236 100644
--- a/include/lib/cpus/aarch32/cpu_macros.S
+++ b/include/lib/cpus/aarch32/cpu_macros.S
@@ -51,11 +51,11 @@
 CPU_MIDR: /* cpu_ops midr */
 	.space  4
 /* Reset fn is needed during reset */
-#if IMAGE_BL1 || IMAGE_BL32
+#if defined(IMAGE_BL1) || defined(IMAGE_BL32)
 CPU_RESET_FUNC: /* cpu_ops reset_func */
 	.space  4
 #endif
-#if IMAGE_BL32 /* The power down core and cluster is needed only in BL32 */
+#ifdef IMAGE_BL32 /* The power down core and cluster is needed only in BL32 */
 CPU_PWR_DWN_OPS: /* cpu_ops power down functions */
 	.space  (4 * CPU_MAX_PWR_DWN_OPS)
 #endif
@@ -117,10 +117,10 @@
 	.align 2
 	.type cpu_ops_\_name, %object
 	.word \_midr
-#if IMAGE_BL1 || IMAGE_BL32
+#if defined(IMAGE_BL1) || defined(IMAGE_BL32)
 	.word \_resetfunc
 #endif
-#if IMAGE_BL32
+#ifdef IMAGE_BL32
 1:
 	/* Insert list of functions */
 	fill_constants CPU_MAX_PWR_DWN_OPS, \_power_down_ops
diff --git a/include/lib/cpus/aarch64/cpu_macros.S b/include/lib/cpus/aarch64/cpu_macros.S
index 570ef88..5012877 100644
--- a/include/lib/cpus/aarch64/cpu_macros.S
+++ b/include/lib/cpus/aarch64/cpu_macros.S
@@ -51,15 +51,15 @@
 CPU_MIDR: /* cpu_ops midr */
 	.space  8
 /* Reset fn is needed in BL at reset vector */
-#if IMAGE_BL1 || IMAGE_BL31
+#if defined(IMAGE_BL1) || defined(IMAGE_BL31)
 CPU_RESET_FUNC: /* cpu_ops reset_func */
 	.space  8
 #endif
-#if IMAGE_BL31 /* The power down core and cluster is needed only in BL31 */
+#ifdef IMAGE_BL31 /* The power down core and cluster is needed only in BL31 */
 CPU_PWR_DWN_OPS: /* cpu_ops power down functions */
 	.space  (8 * CPU_MAX_PWR_DWN_OPS)
 #endif
-#if (IMAGE_BL31 && CRASH_REPORTING)
+#if defined(IMAGE_BL31) && CRASH_REPORTING
 CPU_REG_DUMP: /* cpu specific register dump for crash reporting */
 	.space  8
 #endif
@@ -121,10 +121,10 @@
 	.align 3
 	.type cpu_ops_\_name, %object
 	.quad \_midr
-#if IMAGE_BL1 || IMAGE_BL31
+#if defined(IMAGE_BL1) || defined(IMAGE_BL31)
 	.quad \_resetfunc
 #endif
-#if IMAGE_BL31
+#ifdef IMAGE_BL31
 1:
 	/* Insert list of functions */
 	fill_constants CPU_MAX_PWR_DWN_OPS, \_power_down_ops
@@ -141,7 +141,7 @@
 	  .endif
 	.endif
 #endif
-#if (IMAGE_BL31 && CRASH_REPORTING)
+#if defined(IMAGE_BL31) && CRASH_REPORTING
 	.quad \_name\()_cpu_reg_dump
 #endif
 	.endm
diff --git a/include/lib/libfdt/fdt.h b/include/lib/libfdt/fdt.h
index 6331998..c833dc1 100644
--- a/include/lib/libfdt/fdt.h
+++ b/include/lib/libfdt/fdt.h
@@ -53,7 +53,7 @@
  */
 
 /*
- * Portions copyright (c) 2016, ARM Limited and Contributors.
+ * Portions copyright (c) 2016-2017, ARM Limited and Contributors.
  * All rights reserved.
  */
 
diff --git a/include/lib/libfdt/libfdt.h b/include/lib/libfdt/libfdt.h
index 74f4895..f662378 100644
--- a/include/lib/libfdt/libfdt.h
+++ b/include/lib/libfdt/libfdt.h
@@ -52,7 +52,7 @@
  */
 
 /*
- * Portions copyright (c) 2016, ARM Limited and Contributors.
+ * Portions copyright (c) 2016-2017, ARM Limited and Contributors.
  * All rights reserved.
  */
 
@@ -126,7 +126,12 @@
 	/* FDT_ERR_BADNCELLS: Device tree has a #address-cells, #size-cells
 	 * or similar property with a bad format or value */
 
-#define FDT_ERR_MAX		14
+#define FDT_ERR_BADVALUE	15
+	/* FDT_ERR_BADVALUE: Device tree has a property with an unexpected
+	 * value. For example: a property expected to contain a string list
+	 * is not NUL-terminated within the length of its value. */
+
+#define FDT_ERR_MAX		15
 
 /**********************************************************************/
 /* Low-level functions (you probably don't need these)                */
@@ -168,27 +173,55 @@
  */
 int fdt_next_subnode(const void *fdt, int offset);
 
+/**
+ * fdt_for_each_subnode - iterate over all subnodes of a parent
+ *
+ * @node:	child node (int, lvalue)
+ * @fdt:	FDT blob (const void *)
+ * @parent:	parent node (int)
+ *
+ * This is actually a wrapper around a for loop and would be used like so:
+ *
+ *	fdt_for_each_subnode(node, fdt, parent) {
+ *		Use node
+ *		...
+ *	}
+ *
+ *	if ((node < 0) && (node != -FDT_ERR_NOT_FOUND)) {
+ *		Error handling
+ *	}
+ *
+ * Note that this is implemented as a macro and @node is used as
+ * iterator in the loop. The parent variable be constant or even a
+ * literal.
+ *
+ */
+#define fdt_for_each_subnode(node, fdt, parent)		\
+	for (node = fdt_first_subnode(fdt, parent);	\
+	     node >= 0;					\
+	     node = fdt_next_subnode(fdt, node))
+
 /**********************************************************************/
 /* General functions                                                  */
 /**********************************************************************/
 
 #define fdt_get_header(fdt, field) \
 	(fdt32_to_cpu(((const struct fdt_header *)(fdt))->field))
-#define fdt_magic(fdt) 			(fdt_get_header(fdt, magic))
+#define fdt_magic(fdt)			(fdt_get_header(fdt, magic))
 #define fdt_totalsize(fdt)		(fdt_get_header(fdt, totalsize))
 #define fdt_off_dt_struct(fdt)		(fdt_get_header(fdt, off_dt_struct))
 #define fdt_off_dt_strings(fdt)		(fdt_get_header(fdt, off_dt_strings))
 #define fdt_off_mem_rsvmap(fdt)		(fdt_get_header(fdt, off_mem_rsvmap))
 #define fdt_version(fdt)		(fdt_get_header(fdt, version))
-#define fdt_last_comp_version(fdt) 	(fdt_get_header(fdt, last_comp_version))
-#define fdt_boot_cpuid_phys(fdt) 	(fdt_get_header(fdt, boot_cpuid_phys))
-#define fdt_size_dt_strings(fdt) 	(fdt_get_header(fdt, size_dt_strings))
+#define fdt_last_comp_version(fdt)	(fdt_get_header(fdt, last_comp_version))
+#define fdt_boot_cpuid_phys(fdt)	(fdt_get_header(fdt, boot_cpuid_phys))
+#define fdt_size_dt_strings(fdt)	(fdt_get_header(fdt, size_dt_strings))
 #define fdt_size_dt_struct(fdt)		(fdt_get_header(fdt, size_dt_struct))
 
 #define __fdt_set_hdr(name) \
 	static inline void fdt_set_##name(void *fdt, uint32_t val) \
 	{ \
-		struct fdt_header *fdth = (struct fdt_header*)fdt; \
+		struct fdt_header *fdth = (struct fdt_header *)fdt; \
 		fdth->name = cpu_to_fdt32(val); \
 	}
 __fdt_set_hdr(magic)
@@ -259,6 +292,21 @@
 const char *fdt_string(const void *fdt, int stroffset);
 
 /**
+ * fdt_get_max_phandle - retrieves the highest phandle in a tree
+ * @fdt: pointer to the device tree blob
+ *
+ * fdt_get_max_phandle retrieves the highest phandle in the given
+ * device tree. This will ignore badly formatted phandles, or phandles
+ * with a value of 0 or -1.
+ *
+ * returns:
+ *      the highest phandle on success
+ *      0, if no phandle was found in the device tree
+ *      -1, if an error occurred
+ */
+uint32_t fdt_get_max_phandle(const void *fdt);
+
+/**
  * fdt_num_mem_rsv - retrieve the number of memory reserve map entries
  * @fdt: pointer to the device tree blob
  *
@@ -318,8 +366,9 @@
  * returns:
  *	structure block offset of the requested subnode (>=0), on success
  *	-FDT_ERR_NOTFOUND, if the requested subnode does not exist
- *	-FDT_ERR_BADOFFSET, if parentoffset did not point to an FDT_BEGIN_NODE tag
- *      -FDT_ERR_BADMAGIC,
+ *	-FDT_ERR_BADOFFSET, if parentoffset did not point to an FDT_BEGIN_NODE
+ *		tag
+ *	-FDT_ERR_BADMAGIC,
  *	-FDT_ERR_BADVERSION,
  *	-FDT_ERR_BADSTATE,
  *	-FDT_ERR_BADSTRUCTURE,
@@ -328,6 +377,17 @@
 int fdt_subnode_offset(const void *fdt, int parentoffset, const char *name);
 
 /**
+ * fdt_path_offset_namelen - find a tree node by its full path
+ * @fdt: pointer to the device tree blob
+ * @path: full path of the node to locate
+ * @namelen: number of characters of path to consider
+ *
+ * Identical to fdt_path_offset(), but only consider the first namelen
+ * characters of path as the path name.
+ */
+int fdt_path_offset_namelen(const void *fdt, const char *path, int namelen);
+
+/**
  * fdt_path_offset - find a tree node by its full path
  * @fdt: pointer to the device tree blob
  * @path: full path of the node to locate
@@ -340,7 +400,8 @@
  * address).
  *
  * returns:
- *	structure block offset of the node with the requested path (>=0), on success
+ *	structure block offset of the node with the requested path (>=0), on
+ *		success
  *	-FDT_ERR_BADPATH, given path does not begin with '/' or is invalid
  *	-FDT_ERR_NOTFOUND, if the requested node does not exist
  *      -FDT_ERR_BADMAGIC,
@@ -364,10 +425,12 @@
  *
  * returns:
  *	pointer to the node's name, on success
- *		If lenp is non-NULL, *lenp contains the length of that name (>=0)
+ *		If lenp is non-NULL, *lenp contains the length of that name
+ *			(>=0)
  *	NULL, on error
  *		if lenp is non-NULL *lenp contains an error code (<0):
- *		-FDT_ERR_BADOFFSET, nodeoffset did not point to FDT_BEGIN_NODE tag
+ *		-FDT_ERR_BADOFFSET, nodeoffset did not point to FDT_BEGIN_NODE
+ *			tag
  *		-FDT_ERR_BADMAGIC,
  *		-FDT_ERR_BADVERSION,
  *		-FDT_ERR_BADSTATE, standard meanings
@@ -416,6 +479,33 @@
 int fdt_next_property_offset(const void *fdt, int offset);
 
 /**
+ * fdt_for_each_property_offset - iterate over all properties of a node
+ *
+ * @property_offset:	property offset (int, lvalue)
+ * @fdt:		FDT blob (const void *)
+ * @node:		node offset (int)
+ *
+ * This is actually a wrapper around a for loop and would be used like so:
+ *
+ *	fdt_for_each_property_offset(property, fdt, node) {
+ *		Use property
+ *		...
+ *	}
+ *
+ *	if ((property < 0) && (property != -FDT_ERR_NOT_FOUND)) {
+ *		Error handling
+ *	}
+ *
+ * Note that this is implemented as a macro and property is used as
+ * iterator in the loop. The node variable can be constant or even a
+ * literal.
+ */
+#define fdt_for_each_property_offset(property, fdt, node)	\
+	for (property = fdt_first_property_offset(fdt, node);	\
+	     property >= 0;					\
+	     property = fdt_next_property_offset(fdt, property))
+
+/**
  * fdt_get_property_by_offset - retrieve the property at a given offset
  * @fdt: pointer to the device tree blob
  * @offset: offset of the property to retrieve
@@ -451,8 +541,8 @@
  * @namelen: number of characters of name to consider
  * @lenp: pointer to an integer variable (will be overwritten) or NULL
  *
- * Identical to fdt_get_property_namelen(), but only examine the first
- * namelen characters of name for matching the property name.
+ * Identical to fdt_get_property(), but only examine the first namelen
+ * characters of name for matching the property name.
  */
 const struct fdt_property *fdt_get_property_namelen(const void *fdt,
 						    int nodeoffset,
@@ -479,7 +569,8 @@
  *	NULL, on error
  *		if lenp is non-NULL, *lenp contains an error code (<0):
  *		-FDT_ERR_NOTFOUND, node does not have named property
- *		-FDT_ERR_BADOFFSET, nodeoffset did not point to FDT_BEGIN_NODE tag
+ *		-FDT_ERR_BADOFFSET, nodeoffset did not point to FDT_BEGIN_NODE
+ *			tag
  *		-FDT_ERR_BADMAGIC,
  *		-FDT_ERR_BADVERSION,
  *		-FDT_ERR_BADSTATE,
@@ -543,6 +634,13 @@
  */
 const void *fdt_getprop_namelen(const void *fdt, int nodeoffset,
 				const char *name, int namelen, int *lenp);
+static inline void *fdt_getprop_namelen_w(void *fdt, int nodeoffset,
+					  const char *name, int namelen,
+					  int *lenp)
+{
+	return (void *)(uintptr_t)fdt_getprop_namelen(fdt, nodeoffset, name,
+						      namelen, lenp);
+}
 
 /**
  * fdt_getprop - retrieve the value of a given property
@@ -564,7 +662,8 @@
  *	NULL, on error
  *		if lenp is non-NULL, *lenp contains an error code (<0):
  *		-FDT_ERR_NOTFOUND, node does not have named property
- *		-FDT_ERR_BADOFFSET, nodeoffset did not point to FDT_BEGIN_NODE tag
+ *		-FDT_ERR_BADOFFSET, nodeoffset did not point to FDT_BEGIN_NODE
+ *			tag
  *		-FDT_ERR_BADMAGIC,
  *		-FDT_ERR_BADVERSION,
  *		-FDT_ERR_BADSTATE,
@@ -636,7 +735,7 @@
  *	0, on success
  *		buf contains the absolute path of the node at
  *		nodeoffset, as a NUL-terminated string.
- * 	-FDT_ERR_BADOFFSET, nodeoffset does not refer to a BEGIN_NODE tag
+ *	-FDT_ERR_BADOFFSET, nodeoffset does not refer to a BEGIN_NODE tag
  *	-FDT_ERR_NOSPACE, the path of the given node is longer than (bufsize-1)
  *		characters and will not fit in the given buffer.
  *	-FDT_ERR_BADMAGIC,
@@ -666,11 +765,11 @@
  * structure from the start to nodeoffset.
  *
  * returns:
-
  *	structure block offset of the node at node offset's ancestor
  *		of depth supernodedepth (>=0), on success
- * 	-FDT_ERR_BADOFFSET, nodeoffset does not refer to a BEGIN_NODE tag
-*	-FDT_ERR_NOTFOUND, supernodedepth was greater than the depth of nodeoffset
+ *	-FDT_ERR_BADOFFSET, nodeoffset does not refer to a BEGIN_NODE tag
+ *	-FDT_ERR_NOTFOUND, supernodedepth was greater than the depth of
+ *		nodeoffset
  *	-FDT_ERR_BADMAGIC,
  *	-FDT_ERR_BADVERSION,
  *	-FDT_ERR_BADSTATE,
@@ -692,7 +791,7 @@
  *
  * returns:
  *	depth of the node at nodeoffset (>=0), on success
- * 	-FDT_ERR_BADOFFSET, nodeoffset does not refer to a BEGIN_NODE tag
+ *	-FDT_ERR_BADOFFSET, nodeoffset does not refer to a BEGIN_NODE tag
  *	-FDT_ERR_BADMAGIC,
  *	-FDT_ERR_BADVERSION,
  *	-FDT_ERR_BADSTATE,
@@ -715,7 +814,7 @@
  * returns:
  *	structure block offset of the parent of the node at nodeoffset
  *		(>=0), on success
- * 	-FDT_ERR_BADOFFSET, nodeoffset does not refer to a BEGIN_NODE tag
+ *	-FDT_ERR_BADOFFSET, nodeoffset does not refer to a BEGIN_NODE tag
  *	-FDT_ERR_BADMAGIC,
  *	-FDT_ERR_BADVERSION,
  *	-FDT_ERR_BADSTATE,
@@ -755,7 +854,7 @@
  *		 on success
  *	-FDT_ERR_NOTFOUND, no node matching the criterion exists in the
  *		tree after startoffset
- * 	-FDT_ERR_BADOFFSET, nodeoffset does not refer to a BEGIN_NODE tag
+ *	-FDT_ERR_BADOFFSET, nodeoffset does not refer to a BEGIN_NODE tag
  *	-FDT_ERR_BADMAGIC,
  *	-FDT_ERR_BADVERSION,
  *	-FDT_ERR_BADSTATE,
@@ -802,7 +901,7 @@
  *	1, if the node has a 'compatible' property, but it does not list
  *		the given string
  *	-FDT_ERR_NOTFOUND, if the given node has no 'compatible' property
- * 	-FDT_ERR_BADOFFSET, if nodeoffset does not refer to a BEGIN_NODE tag
+ *	-FDT_ERR_BADOFFSET, if nodeoffset does not refer to a BEGIN_NODE tag
  *	-FDT_ERR_BADMAGIC,
  *	-FDT_ERR_BADVERSION,
  *	-FDT_ERR_BADSTATE,
@@ -839,7 +938,7 @@
  *		 on success
  *	-FDT_ERR_NOTFOUND, no node matching the criterion exists in the
  *		tree after startoffset
- * 	-FDT_ERR_BADOFFSET, nodeoffset does not refer to a BEGIN_NODE tag
+ *	-FDT_ERR_BADOFFSET, nodeoffset does not refer to a BEGIN_NODE tag
  *	-FDT_ERR_BADMAGIC,
  *	-FDT_ERR_BADVERSION,
  *	-FDT_ERR_BADSTATE,
@@ -862,6 +961,68 @@
  */
 int fdt_stringlist_contains(const char *strlist, int listlen, const char *str);
 
+/**
+ * fdt_stringlist_count - count the number of strings in a string list
+ * @fdt: pointer to the device tree blob
+ * @nodeoffset: offset of a tree node
+ * @property: name of the property containing the string list
+ * @return:
+ *   the number of strings in the given property
+ *   -FDT_ERR_BADVALUE if the property value is not NUL-terminated
+ *   -FDT_ERR_NOTFOUND if the property does not exist
+ */
+int fdt_stringlist_count(const void *fdt, int nodeoffset, const char *property);
+
+/**
+ * fdt_stringlist_search - find a string in a string list and return its index
+ * @fdt: pointer to the device tree blob
+ * @nodeoffset: offset of a tree node
+ * @property: name of the property containing the string list
+ * @string: string to look up in the string list
+ *
+ * Note that it is possible for this function to succeed on property values
+ * that are not NUL-terminated. That's because the function will stop after
+ * finding the first occurrence of @string. This can for example happen with
+ * small-valued cell properties, such as #address-cells, when searching for
+ * the empty string.
+ *
+ * @return:
+ *   the index of the string in the list of strings
+ *   -FDT_ERR_BADVALUE if the property value is not NUL-terminated
+ *   -FDT_ERR_NOTFOUND if the property does not exist or does not contain
+ *                     the given string
+ */
+int fdt_stringlist_search(const void *fdt, int nodeoffset, const char *property,
+			  const char *string);
+
+/**
+ * fdt_stringlist_get() - obtain the string at a given index in a string list
+ * @fdt: pointer to the device tree blob
+ * @nodeoffset: offset of a tree node
+ * @property: name of the property containing the string list
+ * @index: index of the string to return
+ * @lenp: return location for the string length or an error code on failure
+ *
+ * Note that this will successfully extract strings from properties with
+ * non-NUL-terminated values. For example on small-valued cell properties
+ * this function will return the empty string.
+ *
+ * If non-NULL, the length of the string (on success) or a negative error-code
+ * (on failure) will be stored in the integer pointer to by lenp.
+ *
+ * @return:
+ *   A pointer to the string at the given index in the string list or NULL on
+ *   failure. On success the length of the string will be stored in the memory
+ *   location pointed to by the lenp parameter, if non-NULL. On failure one of
+ *   the following negative error codes will be returned in the lenp parameter
+ *   (if non-NULL):
+ *     -FDT_ERR_BADVALUE if the property value is not NUL-terminated
+ *     -FDT_ERR_NOTFOUND if the property does not exist
+ */
+const char *fdt_stringlist_get(const void *fdt, int nodeoffset,
+			       const char *property, int index,
+			       int *lenp);
+
 /**********************************************************************/
 /* Read-only functions (addressing related)                           */
 /**********************************************************************/
@@ -887,7 +1048,8 @@
  * returns:
  *	0 <= n < FDT_MAX_NCELLS, on success
  *      2, if the node has no #address-cells property
- *      -FDT_ERR_BADNCELLS, if the node has a badly formatted or invalid #address-cells property
+ *      -FDT_ERR_BADNCELLS, if the node has a badly formatted or invalid
+ *		#address-cells property
  *	-FDT_ERR_BADMAGIC,
  *	-FDT_ERR_BADVERSION,
  *	-FDT_ERR_BADSTATE,
@@ -907,7 +1069,8 @@
  * returns:
  *	0 <= n < FDT_MAX_NCELLS, on success
  *      2, if the node has no #address-cells property
- *      -FDT_ERR_BADNCELLS, if the node has a badly formatted or invalid #size-cells property
+ *      -FDT_ERR_BADNCELLS, if the node has a badly formatted or invalid
+ *		#size-cells property
  *	-FDT_ERR_BADMAGIC,
  *	-FDT_ERR_BADVERSION,
  *	-FDT_ERR_BADSTATE,
@@ -922,6 +1085,27 @@
 /**********************************************************************/
 
 /**
+ * fdt_setprop_inplace_namelen_partial - change a property's value,
+ *                                       but not its size
+ * @fdt: pointer to the device tree blob
+ * @nodeoffset: offset of the node whose property to change
+ * @name: name of the property to change
+ * @namelen: number of characters of name to consider
+ * @idx: index of the property to change in the array
+ * @val: pointer to data to replace the property value with
+ * @len: length of the property value
+ *
+ * Identical to fdt_setprop_inplace(), but modifies the given property
+ * starting from the given index, and using only the first characters
+ * of the name. It is useful when you want to manipulate only one value of
+ * an array and you have a string that doesn't end with \0.
+ */
+int fdt_setprop_inplace_namelen_partial(void *fdt, int nodeoffset,
+					const char *name, int namelen,
+					uint32_t idx, const void *val,
+					int len);
+
+/**
  * fdt_setprop_inplace - change a property's value, but not its size
  * @fdt: pointer to the device tree blob
  * @nodeoffset: offset of the node whose property to change
@@ -1531,9 +1715,11 @@
  * change the offsets of some existing nodes.
 
  * returns:
- *	structure block offset of the created nodeequested subnode (>=0), on success
+ *	structure block offset of the created nodeequested subnode (>=0), on
+ *		success
  *	-FDT_ERR_NOTFOUND, if the requested subnode does not exist
- *	-FDT_ERR_BADOFFSET, if parentoffset did not point to an FDT_BEGIN_NODE tag
+ *	-FDT_ERR_BADOFFSET, if parentoffset did not point to an FDT_BEGIN_NODE
+ *		tag
  *	-FDT_ERR_EXISTS, if the node at parentoffset already has a subnode of
  *		the given name
  *	-FDT_ERR_NOSPACE, if there is insufficient free space in the
diff --git a/include/plat/arm/board/common/board_arm_def.h b/include/plat/arm/board/common/board_arm_def.h
index ad82923..dee868f 100644
--- a/include/plat/arm/board/common/board_arm_def.h
+++ b/include/plat/arm/board/common/board_arm_def.h
@@ -39,23 +39,23 @@
  */
 
 /* Size of cacheable stacks */
-#if IMAGE_BL1
+#if defined(IMAGE_BL1)
 #if TRUSTED_BOARD_BOOT
 # define PLATFORM_STACK_SIZE 0x1000
 #else
 # define PLATFORM_STACK_SIZE 0x440
 #endif
-#elif IMAGE_BL2
+#elif defined(IMAGE_BL2)
 # if TRUSTED_BOARD_BOOT
 #  define PLATFORM_STACK_SIZE 0x1000
 # else
 #  define PLATFORM_STACK_SIZE 0x400
 # endif
-#elif IMAGE_BL2U
+#elif defined(IMAGE_BL2U)
 # define PLATFORM_STACK_SIZE 0x200
-#elif IMAGE_BL31
+#elif defined(IMAGE_BL31)
 # define PLATFORM_STACK_SIZE 0x400
-#elif IMAGE_BL32
+#elif defined(IMAGE_BL32)
 # define PLATFORM_STACK_SIZE 0x440
 #endif
 
@@ -73,7 +73,7 @@
  * Optimisation is less important for the other, transient boot images so a
  * common, maximum value is used across these images.
  */
-#if IMAGE_BL31 || IMAGE_BL32
+#if defined(IMAGE_BL31) || defined(IMAGE_BL32)
 # define PLAT_ARM_MMAP_ENTRIES		6
 # define MAX_XLAT_TABLES		4
 #else
diff --git a/include/plat/arm/common/plat_arm.h b/include/plat/arm/common/plat_arm.h
index c167aa2..e878f9e 100644
--- a/include/plat/arm/common/plat_arm.h
+++ b/include/plat/arm/common/plat_arm.h
@@ -64,7 +64,7 @@
 #endif
 );
 
-#if IMAGE_BL31
+#ifdef IMAGE_BL31
 /*
  * Use this macro to instantiate lock before it is used in below
  * arm_lock_xxx() macros
diff --git a/lib/cpus/aarch32/cpu_helpers.S b/lib/cpus/aarch32/cpu_helpers.S
index 900d158..d8cabfe 100644
--- a/lib/cpus/aarch32/cpu_helpers.S
+++ b/lib/cpus/aarch32/cpu_helpers.S
@@ -34,7 +34,7 @@
 #include <cpu_data.h>
 #include <cpu_macros.S>
 
-#if IMAGE_BL1 || IMAGE_BL32
+#if defined(IMAGE_BL1) || defined(IMAGE_BL32)
 	/*
 	 * The reset handler common to all platforms.  After a matching
 	 * cpu_ops structure entry is found, the correponding reset_handler
@@ -68,7 +68,7 @@
 
 #endif /* IMAGE_BL1 || IMAGE_BL32 */
 
-#if IMAGE_BL32 /* The power down core and cluster is needed only in  BL32 */
+#ifdef IMAGE_BL32 /* The power down core and cluster is needed only in  BL32 */
 	/*
 	 * void prepare_cpu_pwr_dwn(unsigned int power_level)
 	 *
diff --git a/lib/cpus/aarch64/cpu_helpers.S b/lib/cpus/aarch64/cpu_helpers.S
index 4f47439..7365d35 100644
--- a/lib/cpus/aarch64/cpu_helpers.S
+++ b/lib/cpus/aarch64/cpu_helpers.S
@@ -31,14 +31,14 @@
 #include <arch.h>
 #include <asm_macros.S>
 #include <assert_macros.S>
-#if IMAGE_BL31
+#ifdef IMAGE_BL31
 #include <cpu_data.h>
 #endif
 #include <cpu_macros.S>
 #include <debug.h>
 
  /* Reset fn is needed in BL at reset vector */
-#if IMAGE_BL1 || IMAGE_BL31
+#if defined(IMAGE_BL1) || defined(IMAGE_BL31)
 	/*
 	 * The reset handler common to all platforms.  After a matching
 	 * cpu_ops structure entry is found, the correponding reset_handler
@@ -72,7 +72,7 @@
 
 #endif /* IMAGE_BL1 || IMAGE_BL31 */
 
-#if IMAGE_BL31 /* The power down core and cluster is needed only in  BL31 */
+#ifdef IMAGE_BL31 /* The power down core and cluster is needed only in  BL31 */
 	/*
 	 * void prepare_cpu_pwr_dwn(unsigned int power_level)
 	 *
@@ -130,7 +130,7 @@
 endfunc init_cpu_ops
 #endif /* IMAGE_BL31 */
 
-#if IMAGE_BL31 && CRASH_REPORTING
+#if defined(IMAGE_BL31) && CRASH_REPORTING
 	/*
 	 * The cpu specific registers which need to be reported in a crash
 	 * are reported via cpu_ops cpu_reg_dump function. After a matching
diff --git a/lib/el3_runtime/aarch64/context_mgmt.c b/lib/el3_runtime/aarch64/context_mgmt.c
index 35380f3..e26950d 100644
--- a/lib/el3_runtime/aarch64/context_mgmt.c
+++ b/lib/el3_runtime/aarch64/context_mgmt.c
@@ -116,7 +116,7 @@
 	scr_el3 &= ~SCR_EA_BIT;
 #endif
 
-#if IMAGE_BL31
+#ifdef IMAGE_BL31
 	/*
 	 * IRQ/FIQ bits only need setting if interrupt routing
 	 * model has been set up for BL31.
diff --git a/lib/libfdt/fdt.c b/lib/libfdt/fdt.c
index 2ce6a44..22286a1 100644
--- a/lib/libfdt/fdt.c
+++ b/lib/libfdt/fdt.c
@@ -76,18 +76,19 @@
 
 const void *fdt_offset_ptr(const void *fdt, int offset, unsigned int len)
 {
-	const char *p;
+	unsigned absoffset = offset + fdt_off_dt_struct(fdt);
+
+	if ((absoffset < offset)
+	    || ((absoffset + len) < absoffset)
+	    || (absoffset + len) > fdt_totalsize(fdt))
+		return NULL;
 
 	if (fdt_version(fdt) >= 0x11)
 		if (((offset + len) < offset)
 		    || ((offset + len) > fdt_size_dt_struct(fdt)))
 			return NULL;
 
-	p = _fdt_offset_ptr(fdt, offset);
-
-	if (p + len < p)
-		return NULL;
-	return p;
+	return _fdt_offset_ptr(fdt, offset);
 }
 
 uint32_t fdt_next_tag(const void *fdt, int startoffset, int *nextoffset)
diff --git a/lib/libfdt/fdt_ro.c b/lib/libfdt/fdt_ro.c
index 50007f6..0459098 100644
--- a/lib/libfdt/fdt_ro.c
+++ b/lib/libfdt/fdt_ro.c
@@ -88,6 +88,32 @@
 	return (strlen(p) == len) && (memcmp(p, s, len) == 0);
 }
 
+uint32_t fdt_get_max_phandle(const void *fdt)
+{
+	uint32_t max_phandle = 0;
+	int offset;
+
+	for (offset = fdt_next_node(fdt, -1, NULL);;
+	     offset = fdt_next_node(fdt, offset, NULL)) {
+		uint32_t phandle;
+
+		if (offset == -FDT_ERR_NOTFOUND)
+			return max_phandle;
+
+		if (offset < 0)
+			return (uint32_t)-1;
+
+		phandle = fdt_get_phandle(fdt, offset);
+		if (phandle == (uint32_t)-1)
+			continue;
+
+		if (phandle > max_phandle)
+			max_phandle = phandle;
+	}
+
+	return 0;
+}
+
 int fdt_get_mem_rsv(const void *fdt, int n, uint64_t *address, uint64_t *size)
 {
 	FDT_CHECK_HEADER(fdt);
@@ -154,9 +180,9 @@
 	return fdt_subnode_offset_namelen(fdt, parentoffset, name, strlen(name));
 }
 
-int fdt_path_offset(const void *fdt, const char *path)
+int fdt_path_offset_namelen(const void *fdt, const char *path, int namelen)
 {
-	const char *end = path + strlen(path);
+	const char *end = path + namelen;
 	const char *p = path;
 	int offset = 0;
 
@@ -164,7 +190,7 @@
 
 	/* see if we have an alias */
 	if (*path != '/') {
-		const char *q = strchr(path, '/');
+		const char *q = memchr(path, '/', end - p);
 
 		if (!q)
 			q = end;
@@ -177,14 +203,15 @@
 		p = q;
 	}
 
-	while (*p) {
+	while (p < end) {
 		const char *q;
 
-		while (*p == '/')
+		while (*p == '/') {
 			p++;
-		if (! *p)
-			return offset;
-		q = strchr(p, '/');
+			if (p == end)
+				return offset;
+		}
+		q = memchr(p, '/', end - p);
 		if (! q)
 			q = end;
 
@@ -198,6 +225,11 @@
 	return offset;
 }
 
+int fdt_path_offset(const void *fdt, const char *path)
+{
+	return fdt_path_offset_namelen(fdt, path, strlen(path));
+}
+
 const char *fdt_get_name(const void *fdt, int nodeoffset, int *len)
 {
 	const struct fdt_node_header *nh = _fdt_offset_ptr(fdt, nodeoffset);
@@ -532,6 +564,106 @@
 	return 0;
 }
 
+int fdt_stringlist_count(const void *fdt, int nodeoffset, const char *property)
+{
+	const char *list, *end;
+	int length, count = 0;
+
+	list = fdt_getprop(fdt, nodeoffset, property, &length);
+	if (!list)
+		return -length;
+
+	end = list + length;
+
+	while (list < end) {
+		length = strnlen(list, end - list) + 1;
+
+		/* Abort if the last string isn't properly NUL-terminated. */
+		if (list + length > end)
+			return -FDT_ERR_BADVALUE;
+
+		list += length;
+		count++;
+	}
+
+	return count;
+}
+
+int fdt_stringlist_search(const void *fdt, int nodeoffset, const char *property,
+			  const char *string)
+{
+	int length, len, idx = 0;
+	const char *list, *end;
+
+	list = fdt_getprop(fdt, nodeoffset, property, &length);
+	if (!list)
+		return -length;
+
+	len = strlen(string) + 1;
+	end = list + length;
+
+	while (list < end) {
+		length = strnlen(list, end - list) + 1;
+
+		/* Abort if the last string isn't properly NUL-terminated. */
+		if (list + length > end)
+			return -FDT_ERR_BADVALUE;
+
+		if (length == len && memcmp(list, string, length) == 0)
+			return idx;
+
+		list += length;
+		idx++;
+	}
+
+	return -FDT_ERR_NOTFOUND;
+}
+
+const char *fdt_stringlist_get(const void *fdt, int nodeoffset,
+			       const char *property, int idx,
+			       int *lenp)
+{
+	const char *list, *end;
+	int length;
+
+	list = fdt_getprop(fdt, nodeoffset, property, &length);
+	if (!list) {
+		if (lenp)
+			*lenp = length;
+
+		return NULL;
+	}
+
+	end = list + length;
+
+	while (list < end) {
+		length = strnlen(list, end - list) + 1;
+
+		/* Abort if the last string isn't properly NUL-terminated. */
+		if (list + length > end) {
+			if (lenp)
+				*lenp = -FDT_ERR_BADVALUE;
+
+			return NULL;
+		}
+
+		if (idx == 0) {
+			if (lenp)
+				*lenp = length - 1;
+
+			return list;
+		}
+
+		list += length;
+		idx--;
+	}
+
+	if (lenp)
+		*lenp = -FDT_ERR_NOTFOUND;
+
+	return NULL;
+}
+
 int fdt_node_check_compatible(const void *fdt, int nodeoffset,
 			      const char *compatible)
 {
@@ -541,10 +673,8 @@
 	prop = fdt_getprop(fdt, nodeoffset, "compatible", &len);
 	if (!prop)
 		return len;
-	if (fdt_stringlist_contains(prop, len, compatible))
-		return 0;
-	else
-		return 1;
+
+	return !fdt_stringlist_contains(prop, len, compatible);
 }
 
 int fdt_node_offset_by_compatible(const void *fdt, int startoffset,
diff --git a/lib/libfdt/fdt_rw.c b/lib/libfdt/fdt_rw.c
index 70adec6..2eed4f5 100644
--- a/lib/libfdt/fdt_rw.c
+++ b/lib/libfdt/fdt_rw.c
@@ -101,6 +101,8 @@
 
 	if (((p + oldlen) < p) || ((p + oldlen) > end))
 		return -FDT_ERR_BADOFFSET;
+	if ((p < (char *)fdt) || ((end - oldlen + newlen) < (char *)fdt))
+		return -FDT_ERR_BADOFFSET;
 	if ((end - oldlen + newlen) > ((char *)fdt + fdt_totalsize(fdt)))
 		return -FDT_ERR_NOSPACE;
 	memmove(p + newlen, p + oldlen, end - p - oldlen);
@@ -189,17 +191,13 @@
 int fdt_del_mem_rsv(void *fdt, int n)
 {
 	struct fdt_reserve_entry *re = _fdt_mem_rsv_w(fdt, n);
-	int err;
 
 	FDT_RW_CHECK_HEADER(fdt);
 
 	if (n >= fdt_num_mem_rsv(fdt))
 		return -FDT_ERR_NOTFOUND;
 
-	err = _fdt_splice_mem_rsv(fdt, re, 1, 0);
-	if (err)
-		return err;
-	return 0;
+	return _fdt_splice_mem_rsv(fdt, re, 1, 0);
 }
 
 static int _fdt_resize_property(void *fdt, int nodeoffset, const char *name,
diff --git a/lib/libfdt/fdt_wip.c b/lib/libfdt/fdt_wip.c
index c5bbb68..6aaab39 100644
--- a/lib/libfdt/fdt_wip.c
+++ b/lib/libfdt/fdt_wip.c
@@ -55,21 +55,42 @@
 
 #include "libfdt_internal.h"
 
+int fdt_setprop_inplace_namelen_partial(void *fdt, int nodeoffset,
+					const char *name, int namelen,
+					uint32_t idx, const void *val,
+					int len)
+{
+	void *propval;
+	int proplen;
+
+	propval = fdt_getprop_namelen_w(fdt, nodeoffset, name, namelen,
+					&proplen);
+	if (!propval)
+		return proplen;
+
+	if (proplen < (len + idx))
+		return -FDT_ERR_NOSPACE;
+
+	memcpy((char *)propval + idx, val, len);
+	return 0;
+}
+
 int fdt_setprop_inplace(void *fdt, int nodeoffset, const char *name,
 			const void *val, int len)
 {
-	void *propval;
+	const void *propval;
 	int proplen;
 
-	propval = fdt_getprop_w(fdt, nodeoffset, name, &proplen);
+	propval = fdt_getprop(fdt, nodeoffset, name, &proplen);
 	if (! propval)
 		return proplen;
 
 	if (proplen != len)
 		return -FDT_ERR_NOSPACE;
 
-	memcpy(propval, val, len);
-	return 0;
+	return fdt_setprop_inplace_namelen_partial(fdt, nodeoffset, name,
+						   strlen(name), 0,
+						   val, len);
 }
 
 static void _fdt_nop_region(void *start, int len)
diff --git a/make_helpers/build_macros.mk b/make_helpers/build_macros.mk
index bf9dc79..2312d2c 100644
--- a/make_helpers/build_macros.mk
+++ b/make_helpers/build_macros.mk
@@ -227,11 +227,12 @@
 # MAKE_LD generate the linker script using the C preprocessor
 #   $(1) = output linker script
 #   $(2) = input template
+#   $(3) = BL stage (2, 2u, 30, 31, 32, 33)
 define MAKE_LD
 
 $(eval DEP := $(1).d)
 
-$(1): $(2) | $(dir ${1})
+$(1): $(2) | bl$(3)_dirs
 	@echo "  PP      $$<"
 	$$(Q)$$(CPP) $$(CPPFLAGS) -P -D__ASSEMBLY__ -D__LINKER__ $(MAKE_DEP) -o $$@ $$<
 
@@ -297,11 +298,10 @@
         $(eval BL_LINKERFILE := $(BL$(call uppercase,$(1))_LINKERFILE))
         # We use sort only to get a list of unique object directory names.
         # ordering is not relevant but sort removes duplicates.
-        $(eval TEMP_OBJ_DIRS := $(sort $(BUILD_DIR)/ $(dir ${OBJS})))
+        $(eval TEMP_OBJ_DIRS := $(sort $(BUILD_DIR)/ $(dir ${OBJS} ${LINKERFILE})))
         # The $(dir ) function leaves a trailing / on the directory names
-        # We append a . then strip /. from each, to remove the trailing / characters
-        # This gives names suitable for use as make rule targets.
-        $(eval OBJ_DIRS   := $(subst /.,,$(addsuffix .,$(TEMP_OBJ_DIRS))))
+        # Rip off the / to match directory names with make rule targets.
+        $(eval OBJ_DIRS   := $(patsubst %/,%,$(TEMP_OBJ_DIRS)))
 
 # Create generators for object directory structure
 
@@ -314,7 +314,7 @@
 bl${1}_dirs: | ${OBJ_DIRS}
 
 $(eval $(call MAKE_OBJS,$(BUILD_DIR),$(SOURCES),$(1)))
-$(eval $(call MAKE_LD,$(LINKERFILE),$(BL_LINKERFILE)))
+$(eval $(call MAKE_LD,$(LINKERFILE),$(BL_LINKERFILE),$(1)))
 
 $(ELF): $(OBJS) $(LINKERFILE) | bl$(1)_dirs
 	@echo "  LD      $$@"
diff --git a/plat/arm/board/common/board_css_common.c b/plat/arm/board/common/board_css_common.c
index 69b744d..3fcc6ee 100644
--- a/plat/arm/board/common/board_css_common.c
+++ b/plat/arm/board/common/board_css_common.c
@@ -35,7 +35,7 @@
  * This doesn't include Trusted SRAM as arm_setup_page_tables() already
  * takes care of mapping it.
  */
-#if IMAGE_BL1
+#ifdef IMAGE_BL1
 const mmap_region_t plat_arm_mmap[] = {
 	ARM_MAP_SHARED_RAM,
 	V2M_MAP_FLASH0_RO,
@@ -48,7 +48,7 @@
 	{0}
 };
 #endif
-#if IMAGE_BL2
+#ifdef IMAGE_BL2
 const mmap_region_t plat_arm_mmap[] = {
 	ARM_MAP_SHARED_RAM,
 	V2M_MAP_FLASH0_RO,
@@ -60,7 +60,7 @@
 	{0}
 };
 #endif
-#if IMAGE_BL2U
+#ifdef IMAGE_BL2U
 const mmap_region_t plat_arm_mmap[] = {
 	ARM_MAP_SHARED_RAM,
 	CSS_MAP_DEVICE,
@@ -68,7 +68,7 @@
 	{0}
 };
 #endif
-#if IMAGE_BL31
+#ifdef IMAGE_BL31
 const mmap_region_t plat_arm_mmap[] = {
 	ARM_MAP_SHARED_RAM,
 	V2M_MAP_IOFPGA,
@@ -77,7 +77,7 @@
 	{0}
 };
 #endif
-#if IMAGE_BL32
+#ifdef IMAGE_BL32
 const mmap_region_t plat_arm_mmap[] = {
 	V2M_MAP_IOFPGA,
 	CSS_MAP_DEVICE,
diff --git a/plat/arm/board/fvp/fvp_common.c b/plat/arm/board/fvp/fvp_common.c
index 3df472c..e201101 100644
--- a/plat/arm/board/fvp/fvp_common.c
+++ b/plat/arm/board/fvp/fvp_common.c
@@ -73,7 +73,7 @@
  * The flash needs to be mapped as writable in order to erase the FIP's Table of
  * Contents in case of unrecoverable error (see plat_error_handler()).
  */
-#if IMAGE_BL1
+#ifdef IMAGE_BL1
 const mmap_region_t plat_arm_mmap[] = {
 	ARM_MAP_SHARED_RAM,
 	V2M_MAP_FLASH0_RW,
@@ -87,7 +87,7 @@
 	{0}
 };
 #endif
-#if IMAGE_BL2
+#ifdef IMAGE_BL2
 const mmap_region_t plat_arm_mmap[] = {
 	ARM_MAP_SHARED_RAM,
 	V2M_MAP_FLASH0_RW,
@@ -103,14 +103,14 @@
 	{0}
 };
 #endif
-#if IMAGE_BL2U
+#ifdef IMAGE_BL2U
 const mmap_region_t plat_arm_mmap[] = {
 	MAP_DEVICE0,
 	V2M_MAP_IOFPGA,
 	{0}
 };
 #endif
-#if IMAGE_BL31
+#ifdef IMAGE_BL31
 const mmap_region_t plat_arm_mmap[] = {
 	ARM_MAP_SHARED_RAM,
 	V2M_MAP_IOFPGA,
@@ -119,7 +119,7 @@
 	{0}
 };
 #endif
-#if IMAGE_BL32
+#ifdef IMAGE_BL32
 const mmap_region_t plat_arm_mmap[] = {
 #ifdef AARCH32
 	ARM_MAP_SHARED_RAM,
diff --git a/plat/arm/board/juno/include/platform_def.h b/plat/arm/board/juno/include/platform_def.h
index adc4704..f89f7b4 100644
--- a/plat/arm/board/juno/include/platform_def.h
+++ b/plat/arm/board/juno/include/platform_def.h
@@ -82,27 +82,27 @@
  * PLAT_ARM_MMAP_ENTRIES depends on the number of entries in the
  * plat_arm_mmap array defined for each BL stage.
  */
-#if IMAGE_BL1
+#ifdef IMAGE_BL1
 # define PLAT_ARM_MMAP_ENTRIES		7
 # define MAX_XLAT_TABLES		4
 #endif
 
-#if IMAGE_BL2
+#ifdef IMAGE_BL2
 # define PLAT_ARM_MMAP_ENTRIES		8
 # define MAX_XLAT_TABLES		3
 #endif
 
-#if IMAGE_BL2U
+#ifdef IMAGE_BL2U
 # define PLAT_ARM_MMAP_ENTRIES		4
 # define MAX_XLAT_TABLES		3
 #endif
 
-#if IMAGE_BL31
+#ifdef IMAGE_BL31
 # define PLAT_ARM_MMAP_ENTRIES		5
 # define MAX_XLAT_TABLES		2
 #endif
 
-#if IMAGE_BL32
+#ifdef IMAGE_BL32
 # define PLAT_ARM_MMAP_ENTRIES		4
 # define MAX_XLAT_TABLES		3
 #endif
diff --git a/plat/arm/common/arm_gicv3.c b/plat/arm/common/arm_gicv3.c
index 6d68bfb..fd0f101 100644
--- a/plat/arm/common/arm_gicv3.c
+++ b/plat/arm/common/arm_gicv3.c
@@ -79,7 +79,8 @@
 	 * can use GIC system registers to manage interrupts and does
 	 * not need GIC interface base addresses to be configured.
 	 */
-#if (AARCH32 && IMAGE_BL32) || (IMAGE_BL31 && !AARCH32)
+#if (defined(AARCH32) && defined(IMAGE_BL32)) || \
+	(defined(IMAGE_BL31) && !defined(AARCH32))
 	gicv3_driver_init(&arm_gic_data);
 #endif
 }
diff --git a/plat/common/plat_gicv3.c b/plat/common/plat_gicv3.c
index c961d62..3bea013 100644
--- a/plat/common/plat_gicv3.c
+++ b/plat/common/plat_gicv3.c
@@ -36,7 +36,7 @@
 #include <interrupt_mgmt.h>
 #include <platform.h>
 
-#if IMAGE_BL31
+#ifdef IMAGE_BL31
 
 /*
  * The following platform GIC functions are weakly defined. They
@@ -180,7 +180,7 @@
 	}
 }
 #endif
-#if IMAGE_BL32
+#ifdef IMAGE_BL32
 
 #pragma weak plat_ic_get_pending_interrupt_id
 #pragma weak plat_ic_acknowledge_interrupt
diff --git a/plat/mediatek/mt6795/include/platform_def.h b/plat/mediatek/mt6795/include/platform_def.h
index 275333f..16b3d39 100644
--- a/plat/mediatek/mt6795/include/platform_def.h
+++ b/plat/mediatek/mt6795/include/platform_def.h
@@ -156,13 +156,13 @@
 /* Size of cacheable stacks */
 #if DEBUG_XLAT_TABLE
 #define PLATFORM_STACK_SIZE 0x800
-#elif IMAGE_BL1
+#elif defined(IMAGE_BL1)
 #define PLATFORM_STACK_SIZE 0x440
-#elif IMAGE_BL2
+#elif defined(IMAGE_BL2)
 #define PLATFORM_STACK_SIZE 0x400
-#elif IMAGE_BL31
+#elif defined(IMAGE_BL31)
 #define PLATFORM_STACK_SIZE 0x800
-#elif IMAGE_BL32
+#elif defined(IMAGE_BL32)
 #define PLATFORM_STACK_SIZE 0x440
 #endif
 
diff --git a/plat/mediatek/mt8173/include/platform_def.h b/plat/mediatek/mt8173/include/platform_def.h
index dc5b000..8f771e3 100644
--- a/plat/mediatek/mt8173/include/platform_def.h
+++ b/plat/mediatek/mt8173/include/platform_def.h
@@ -43,13 +43,13 @@
  ******************************************************************************/
 
 /* Size of cacheable stacks */
-#if IMAGE_BL1
+#if defined(IMAGE_BL1)
 #define PLATFORM_STACK_SIZE 0x440
-#elif IMAGE_BL2
+#elif defined(IMAGE_BL2)
 #define PLATFORM_STACK_SIZE 0x400
-#elif IMAGE_BL31
+#elif defined(IMAGE_BL31)
 #define PLATFORM_STACK_SIZE 0x800
-#elif IMAGE_BL32
+#elif defined(IMAGE_BL32)
 #define PLATFORM_STACK_SIZE 0x440
 #endif
 
diff --git a/plat/nvidia/tegra/include/platform_def.h b/plat/nvidia/tegra/include/platform_def.h
index 70ddaa9..cd06d93 100644
--- a/plat/nvidia/tegra/include/platform_def.h
+++ b/plat/nvidia/tegra/include/platform_def.h
@@ -40,7 +40,7 @@
  ******************************************************************************/
 
 /* Size of cacheable stacks */
-#if IMAGE_BL31
+#ifdef IMAGE_BL31
 #define PLATFORM_STACK_SIZE 0x400
 #endif
 
diff --git a/plat/qemu/qemu_common.c b/plat/qemu/qemu_common.c
index 7ba1d34..0fe7df1 100644
--- a/plat/qemu/qemu_common.c
+++ b/plat/qemu/qemu_common.c
@@ -68,7 +68,7 @@
  * This doesn't include TZRAM as the 'mem_layout' argument passed to
  * arm_configure_mmu_elx() will give the available subset of that,
  */
-#if IMAGE_BL1
+#ifdef IMAGE_BL1
 static const mmap_region_t plat_qemu_mmap[] = {
 	MAP_FLASH0,
 	MAP_SHARED_RAM,
@@ -82,7 +82,7 @@
 	{0}
 };
 #endif
-#if IMAGE_BL2
+#ifdef IMAGE_BL2
 static const mmap_region_t plat_qemu_mmap[] = {
 	MAP_FLASH0,
 	MAP_SHARED_RAM,
@@ -98,7 +98,7 @@
 	{0}
 };
 #endif
-#if IMAGE_BL31
+#ifdef IMAGE_BL31
 static const mmap_region_t plat_qemu_mmap[] = {
 	MAP_SHARED_RAM,
 	MAP_DEVICE0,
diff --git a/plat/rockchip/common/rockchip_gicv3.c b/plat/rockchip/common/rockchip_gicv3.c
index 7730896..f3d306e 100644
--- a/plat/rockchip/common/rockchip_gicv3.c
+++ b/plat/rockchip/common/rockchip_gicv3.c
@@ -82,7 +82,7 @@
 	 * can use GIC system registers to manage interrupts and does
 	 * not need GIC interface base addresses to be configured.
 	 */
-#if IMAGE_BL31
+#ifdef IMAGE_BL31
 	gicv3_driver_init(&rockchip_gic_data);
 #endif
 }
diff --git a/plat/rockchip/rk3368/include/platform_def.h b/plat/rockchip/rk3368/include/platform_def.h
index 5d801cf..d72893c 100644
--- a/plat/rockchip/rk3368/include/platform_def.h
+++ b/plat/rockchip/rk3368/include/platform_def.h
@@ -50,13 +50,13 @@
 /* Size of cacheable stacks */
 #if DEBUG_XLAT_TABLE
 #define PLATFORM_STACK_SIZE 0x800
-#elif IMAGE_BL1
+#elif defined(IMAGE_BL1)
 #define PLATFORM_STACK_SIZE 0x440
-#elif IMAGE_BL2
+#elif defined(IMAGE_BL2)
 #define PLATFORM_STACK_SIZE 0x400
-#elif IMAGE_BL31
+#elif defined(IMAGE_BL31)
 #define PLATFORM_STACK_SIZE 0x800
-#elif IMAGE_BL32
+#elif defined(IMAGE_BL32)
 #define PLATFORM_STACK_SIZE 0x440
 #endif
 
diff --git a/plat/rockchip/rk3399/include/platform_def.h b/plat/rockchip/rk3399/include/platform_def.h
index b494824..5ccc532 100644
--- a/plat/rockchip/rk3399/include/platform_def.h
+++ b/plat/rockchip/rk3399/include/platform_def.h
@@ -50,13 +50,13 @@
 /* Size of cacheable stacks */
 #if DEBUG_XLAT_TABLE
 #define PLATFORM_STACK_SIZE 0x800
-#elif IMAGE_BL1
+#elif defined(IMAGE_BL1)
 #define PLATFORM_STACK_SIZE 0x440
-#elif IMAGE_BL2
+#elif defined(IMAGE_BL2)
 #define PLATFORM_STACK_SIZE 0x400
-#elif IMAGE_BL31
+#elif defined(IMAGE_BL31)
 #define PLATFORM_STACK_SIZE 0x800
-#elif IMAGE_BL32
+#elif defined(IMAGE_BL32)
 #define PLATFORM_STACK_SIZE 0x440
 #endif
 
diff --git a/tools/fiptool/fiptool.c b/tools/fiptool/fiptool.c
index fc0c8d6..6145e26 100644
--- a/tools/fiptool/fiptool.c
+++ b/tools/fiptool/fiptool.c
@@ -155,12 +155,17 @@
 	return d;
 }
 
+static void *xzalloc(size_t size, const char *msg)
+{
+	return memset(xmalloc(size, msg), 0, size);
+}
+
 static image_desc_t *new_image_desc(const uuid_t *uuid,
     const char *name, const char *cmdline_name)
 {
 	image_desc_t *desc;
 
-	desc = xmalloc(sizeof(*desc),
+	desc = xzalloc(sizeof(*desc),
 	    "failed to allocate memory for image descriptor");
 	memcpy(&desc->uuid, uuid, sizeof(uuid_t));
 	desc->name = xstrdup(name,
@@ -168,7 +173,6 @@
 	desc->cmdline_name = xstrdup(cmdline_name,
 	    "failed to allocate memory for image command line name");
 	desc->action = DO_UNSPEC;
-	desc->action_arg = NULL;
 	return desc;
 }
 
@@ -196,9 +200,14 @@
 
 static void add_image_desc(image_desc_t *desc)
 {
+	image_desc_t **p = &image_desc_head;
+
 	assert(lookup_image_desc_from_uuid(&desc->uuid) == NULL);
-	desc->next = image_desc_head;
-	image_desc_head = desc;
+
+	while (*p)
+		p = &(*p)->next;
+
+	*p = desc;
 	nr_image_descs++;
 }
 
@@ -233,9 +242,15 @@
 
 static void add_image(image_t *image)
 {
+	image_t **p = &image_head;
+
 	assert(lookup_image_from_uuid(&image->uuid) == NULL);
-	image->next = image_head;
-	image_head = image;
+
+	while (*p)
+		p = &(*p)->next;
+
+	*p = image;
+
 	nr_images++;
 }
 
@@ -393,7 +408,7 @@
 		 * Build a new image out of the ToC entry and add it to the
 		 * table of images.
 		 */
-		image = xmalloc(sizeof(*image),
+		image = xzalloc(sizeof(*image),
 		    "failed to allocate memory for image");
 		memcpy(&image->uuid, &toc_entry->uuid, sizeof(uuid_t));
 		image->buffer = xmalloc(toc_entry->size,
@@ -450,7 +465,7 @@
 	if (fstat(fileno(fp), &st) == -1)
 		log_errx("fstat %s", filename);
 
-	image = xmalloc(sizeof(*image), "failed to allocate memory for image");
+	image = xzalloc(sizeof(*image), "failed to allocate memory for image");
 	memcpy(&image->uuid, uuid, sizeof(uuid_t));
 	image->buffer = xmalloc(st.st_size, "failed to allocate image buffer");
 	if (fread(image->buffer, 1, st.st_size, fp) != st.st_size)