Merge git://git.denx.de/u-boot-rockchip
diff --git a/arch/arm/include/asm/arch-rockchip/boot0.h b/arch/arm/include/asm/arch-rockchip/boot0.h
index af3a733..5d35c35 100644
--- a/arch/arm/include/asm/arch-rockchip/boot0.h
+++ b/arch/arm/include/asm/arch-rockchip/boot0.h
@@ -39,7 +39,12 @@
 entry_counter:
 	.word   0
 #endif
+
+#if (defined(CONFIG_SPL_BUILD) || defined(CONFIG_ARM64))
+	/* U-Boot proper of armv7 do not need this */
 	b reset
+#endif
+
 #if !defined(CONFIG_ARM64)
 	/*
 	 * For armv7, the addr '_start' will used as vector start address
@@ -50,6 +55,6 @@
 	ARM_VECTORS
 #endif
 
-#if defined(CONFIG_ROCKCHIP_RK3399) && defined(CONFIG_SPL_BUILD)
+#if defined(CONFIG_SPL_BUILD) && (CONFIG_ROCKCHIP_SPL_RESERVE_IRAM > 0)
 	.space CONFIG_ROCKCHIP_SPL_RESERVE_IRAM	/* space for the ATF data */
 #endif
diff --git a/arch/arm/mach-rockchip/Kconfig b/arch/arm/mach-rockchip/Kconfig
index 1e74db3..967290f 100644
--- a/arch/arm/mach-rockchip/Kconfig
+++ b/arch/arm/mach-rockchip/Kconfig
@@ -179,7 +179,7 @@
 
 config ROCKCHIP_SPL_RESERVE_IRAM
 	hex "Size of IRAM reserved in SPL"
-	default 0x4000
+	default 0
 	help
 	  SPL may need reserve memory for firmware loaded by SPL, whose load
 	  address is in IRAM and may overlay with SPL text area if not
diff --git a/arch/arm/mach-rockchip/make_fit_atf.py b/arch/arm/mach-rockchip/make_fit_atf.py
new file mode 100755
index 0000000..7c6dd57
--- /dev/null
+++ b/arch/arm/mach-rockchip/make_fit_atf.py
@@ -0,0 +1,221 @@
+#!/usr/bin/env python2
+"""
+A script to generate FIT image source for rockchip boards
+with ARM Trusted Firmware
+and multiple device trees (given on the command line)
+
+usage: $0 <dt_name> [<dt_name> [<dt_name] ...]
+"""
+
+import os
+import sys
+import getopt
+
+# pip install pyelftools
+from elftools.elf.elffile import ELFFile
+from elftools.elf.sections import SymbolTableSection
+from elftools.elf.segments import Segment, InterpSegment, NoteSegment
+
+ELF_SEG_P_TYPE='p_type'
+ELF_SEG_P_PADDR='p_paddr'
+ELF_SEG_P_VADDR='p_vaddr'
+ELF_SEG_P_OFFSET='p_offset'
+ELF_SEG_P_FILESZ='p_filesz'
+ELF_SEG_P_MEMSZ='p_memsz'
+
+DT_HEADER="""/*
+ * Copyright (C) 2017 Fuzhou Rockchip Electronics Co., Ltd
+ *
+ * Minimal dts for a SPL FIT image payload.
+ *
+ * SPDX-License-Identifier: GPL-2.0+  X11
+ */
+/dts-v1/;
+
+/ {
+	description = "Configuration to load ATF before U-Boot";
+	#address-cells = <1>;
+
+	images {
+		uboot@1 {
+			description = "U-Boot (64-bit)";
+			data = /incbin/("u-boot-nodtb.bin");
+			type = "standalone";
+			os = "U-Boot";
+			arch = "arm64";
+			compression = "none";
+			load = <0x%08x>;
+		};
+"""
+
+DT_IMAGES_NODE_END="""
+    };
+"""
+
+DT_END="""
+};
+"""
+
+def append_atf_node(file, atf_index, phy_addr):
+    """
+    Append ATF DT node to input FIT dts file.
+    """
+    data = 'bl31_0x%08x.bin' % phy_addr
+    print >> file, '\t\tatf@%d {' % atf_index
+    print >> file, '\t\t\tdescription = \"ARM Trusted Firmware\";'
+    print >> file, '\t\t\tdata = /incbin/("%s");' % data
+    print >> file, '\t\t\ttype = "firmware";'
+    print >> file, '\t\t\tarch = "arm64";'
+    print >> file, '\t\t\tos = "arm-trusted-firmware";'
+    print >> file, '\t\t\tcompression = "none";'
+    print >> file, '\t\t\tload = <0x%08x>;' % phy_addr
+    if atf_index == 1:
+        print >> file, '\t\t\tentry = <0x%08x>;' % phy_addr
+    print >> file, '\t\t};'
+    print >> file, ''
+
+def append_fdt_node(file, dtbs):
+    """
+    Append FDT nodes.
+    """
+    cnt = 1
+    for dtb in dtbs:
+        dtname = os.path.basename(dtb)
+        print >> file, '\t\tfdt@%d {' % cnt
+        print >> file, '\t\t\tdescription = "%s";' % dtname
+        print >> file, '\t\t\tdata = /incbin/("%s");' % dtb
+        print >> file, '\t\t\ttype = "flat_dt";'
+        print >> file, '\t\t\tcompression = "none";'
+        print >> file, '\t\t};'
+        print >> file, ''
+        cnt = cnt + 1
+
+def append_conf_section(file, cnt, dtname, atf_cnt):
+    print >> file, '\t\tconfig@%d {' % cnt
+    print >> file, '\t\t\tdescription = "%s";' % dtname
+    print >> file, '\t\t\tfirmware = "atf@1";'
+    print >> file, '\t\t\tloadables = "uboot@1",',
+    for i in range(1, atf_cnt):
+        print >> file, '"atf@%d"' % (i+1),
+        if i != (atf_cnt - 1):
+            print >> file, ',',
+        else:
+            print >> file, ';'
+    print >> file, '\t\t\tfdt = "fdt@1";'
+    print >> file, '\t\t};'
+    print >> file, ''
+
+def append_conf_node(file, dtbs, atf_cnt):
+    """
+    Append configeration nodes.
+    """
+    cnt = 1
+    print >> file, '\tconfigurations {'
+    print >> file, '\t\tdefault = "config@1";'
+    for dtb in dtbs:
+        dtname = os.path.basename(dtb)
+        append_conf_section(file, cnt, dtname, atf_cnt)
+        cnt = cnt + 1
+    print >> file, '\t};'
+    print >> file, ''
+
+def generate_atf_fit_dts(fit_file_name, bl31_file_name, uboot_file_name, dtbs_file_name):
+    """
+    Generate FIT script for ATF image.
+    """
+    if fit_file_name != sys.stdout:
+        fit_file = open(fit_file_name, "wb")
+    else:
+        fit_file = sys.stdout
+
+    num_load_seg = 0
+    p_paddr = 0xFFFFFFFF
+    with open(uboot_file_name) as uboot_file:
+        uboot = ELFFile(uboot_file)
+        for i in range(uboot.num_segments()):
+            seg = uboot.get_segment(i)
+            if ('PT_LOAD' == seg.__getitem__(ELF_SEG_P_TYPE)):
+                p_paddr = seg.__getitem__(ELF_SEG_P_PADDR)
+                num_load_seg = num_load_seg + 1
+
+    assert (p_paddr != 0xFFFFFFFF and num_load_seg == 1)
+
+    print >> fit_file, DT_HEADER % p_paddr
+
+    with open(bl31_file_name) as bl31_file:
+        bl31 = ELFFile(bl31_file)
+        for i in range(bl31.num_segments()):
+            seg = bl31.get_segment(i)
+            if ('PT_LOAD' == seg.__getitem__(ELF_SEG_P_TYPE)):
+                paddr = seg.__getitem__(ELF_SEG_P_PADDR)
+                p= seg.__getitem__(ELF_SEG_P_PADDR)
+                append_atf_node(fit_file, i+1, paddr)
+    atf_cnt = i+1
+    append_fdt_node(fit_file, dtbs_file_name)
+    print >> fit_file, '%s' % DT_IMAGES_NODE_END
+    append_conf_node(fit_file, dtbs_file_name, atf_cnt)
+    print >> fit_file, '%s' % DT_END
+
+    if fit_file_name != sys.stdout:
+        fit_file.close()
+
+def generate_atf_binary(bl31_file_name):
+    with open(bl31_file_name) as bl31_file:
+        bl31 = ELFFile(bl31_file)
+
+        num = bl31.num_segments()
+        for i in range(num):
+            seg = bl31.get_segment(i)
+            if ('PT_LOAD' == seg.__getitem__(ELF_SEG_P_TYPE)):
+                paddr = seg.__getitem__(ELF_SEG_P_PADDR)
+                file_name = 'bl31_0x%08x.bin' % paddr
+                with open(file_name, "wb") as atf:
+                    atf.write(seg.data());
+
+def get_bl31_segments_info(bl31_file_name):
+    """
+    Get load offset, physical offset, file size
+    from bl31 elf file program headers.
+    """
+    with open(bl31_file_name) as bl31_file:
+        bl31 = ELFFile(bl31_file)
+
+        num = bl31.num_segments()
+        print 'Number of Segments : %d' % bl31.num_segments()
+        for i in range(num):
+            print 'Segment %d' % i
+            seg = bl31.get_segment(i)
+            ptype = seg[ELF_SEG_P_TYPE]
+            poffset = seg[ELF_SEG_P_OFFSET]
+            pmemsz = seg[ELF_SEG_P_MEMSZ]
+            pfilesz = seg[ELF_SEG_P_FILESZ]
+            print 'type: %s\nfilesz: %08x\nmemsz: %08x\noffset: %08x' % (ptype, pfilesz, pmemsz, poffset)
+            paddr = seg[ELF_SEG_P_PADDR]
+            print 'paddr: %08x' % paddr
+
+def main():
+    uboot_elf="./u-boot"
+    bl31_elf="./bl31.elf"
+    FIT_ITS=sys.stdout
+
+    opts, args = getopt.getopt(sys.argv[1:], "o:u:b:h")
+    for opt, val in opts:
+        if opt == "-o":
+            FIT_ITS=val
+        elif opt == "-u":
+            uboot_elf=val
+        elif opt == "-b":
+            bl31_elf=val
+        elif opt == "-h":
+            print __doc__
+            sys.exit(2)
+
+    dtbs = args
+    #get_bl31_segments_info("u-boot")
+    #get_bl31_segments_info("bl31.elf")
+
+    generate_atf_fit_dts(FIT_ITS, bl31_elf, uboot_elf, dtbs)
+    generate_atf_binary(bl31_elf);
+
+if __name__ == "__main__":
+    main()
diff --git a/board/rockchip/evb_rk3399/README b/board/rockchip/evb_rk3399/README
index fb8bb19..ada8ca7 100644
--- a/board/rockchip/evb_rk3399/README
+++ b/board/rockchip/evb_rk3399/README
@@ -18,8 +18,8 @@
 * PMIC: rk808
 * debug console: UART2
 
-In order to support Arm Trust Firmware(ATF), we need to use the
-miniloader from rockchip which:
+In order to support Arm Trust Firmware(ATF), we can use either SPL or
+miniloader from rockchip to do:
 * do DRAM init
 * load and verify ATF image
 * load and verify U-Boot image
@@ -32,8 +32,8 @@
   > mkdir ~/evb_rk3399
   > cd ~/evb_rk3399
   > git clone https://github.com/ARM-software/arm-trusted-firmware.git
-  > git clone https://github.com/rockchip-linux/rkbin
-  > git clone https://github.com/rockchip-linux/rkflashtool
+  > git clone https://github.com/rockchip-linux/rkbin.git
+  > git clone https://github.com/rockchip-linux/rkdeveloptool.git
 
 Compile the ATF
 ===============
@@ -42,32 +42,79 @@
   > make realclean
   > make CROSS_COMPILE=aarch64-linux-gnu- PLAT=rk3399 bl31
 
+  Or you can get the bl31.elf directly from Rockchip:
+  cp rkbin/rk33/rk3399_bl31_v1.00.elf ../u-boot/bl31.elf
+
+  Get bl31.elf in this step, copy it to U-Boot root dir:
+  > cp bl31.elf ../u-boot/
+
 Compile the U-Boot
 ==================
 
   > cd ../u-boot
-  > make CROSS_COMPILE=aarch64-linux-gnu- evb-rk3399_defconfig all
-
-Compile the rkflashtool
-=======================
-
-  > cd ../rkflashtool
+  > export ARCH=arm64
+  > export CROSS_COMPILE=aarch64-linux-gnu-
+  > make evb-rk3399_defconfig
+  for firefly-rk3399, use below instead:
+  > make firefly-rk3399_defconfig
   > make
+  > make u-boot.itb
 
-Package the image for miniloader
-================================
+  Get spl/u-boot-spl.bin and u-boot.itb in this step.
+
+Compile the rkdeveloptool
+=======================
+  Follow instructions in latest README
+  > cd ../rkflashtool
+  > autoreconf -i
+  > ./configure
+  > make
+  > sudo make install
+
+  Get rkdeveloptool in you Host in this step.
+
+Both origin binaries and Tool are ready now, choose either option 1 or
+option 2 to deploy U-Boot.
+
+Package the image
+=================
+
+Package the image for U-Boot SPL(option 1)
+--------------------------------
   > cd ..
-  > cp arm-trusted-firmware/build/rk3399/release/bl31.bin rkbin/rk33
+  > tools/mkimage -n rk3399 -T rksd -d spl/u-boot-spl.bin idbspl.img
+
+  Get idbspl.img in this step.
+
+Package the image for Rockchip miniloader(option 2)
+------------------------------------------
+  > cd ..
+  > cp arm-trusted-firmware/build/rk3399/release/bl31.elf rkbin/rk33
   > ./rkbin/tools/trust_merger rkbin/tools/RK3399TRUST.ini
   > ./rkbin/tools/loaderimage --pack --uboot u-boot/u-boot-dtb.bin uboot.img
-  > mkdir image
-  > mv trust.img ./image/
-  > mv uboot.img ./image/rk3399evb-uboot.bin
 
-Flash the image
-===============
+  Get trust.img and uboot.img in this step.
+
+Flash the image to eMMC
+=======================
+
+Flash the image with U-Boot SPL(option 1)
+-------------------------------
 Power on(or reset with RESET KEY) with MASKROM KEY preesed, and then:
+  > rkdeveloptool db rkbin/rk33/rk3399_loader_v1.08.106.bin
+  > rkdeveloptool wl 64 u-boot/idbspl.img
+  > rkdeveloptool wl 0x4000 u-boot/u-boot.itb
+  > rkdeveloptool rd
 
-  > ./rkflashtool/rkflashloader rk3399evb
+Flash the image with Rockchip miniloader(option 2)
+----------------------------------------
+Power on(or reset with RESET KEY) with MASKROM KEY preesed, and then:
+  > rkdeveloptool db rkbin/rk33/rk3399_loader_v1.08.106.bin
+  > rkdeveloptool ul rkbin/rk33/rk3399_loader_v1.08.106.bin
+  > rkdeveloptool wl 0x4000 u-boot/uboot.img
+  > rkdeveloptool wl 0x6000 u-boot/trust.img
+  > rkdeveloptool rd
 
-You should be able to get U-Boot log message in console/UART2 now.
+You should be able to get U-Boot log in console/UART2(baurdrate 1500000)
+For more detail, please reference to:
+http://opensource.rock-chips.com/wiki_Boot_option
diff --git a/board/theobroma-systems/puma_rk3399/Kconfig b/board/theobroma-systems/puma_rk3399/Kconfig
index a645590..80b3460 100644
--- a/board/theobroma-systems/puma_rk3399/Kconfig
+++ b/board/theobroma-systems/puma_rk3399/Kconfig
@@ -12,4 +12,10 @@
 config BOARD_SPECIFIC_OPTIONS # dummy
 	def_bool y
 
+config ENV_SIZE
+	default 0x2000 if ENV_IS_IN_SPI_FLASH
+
+config ENV_OFFSET
+	default 0x3c000 if ENV_IS_IN_SPI_FLASH
+
 endif
diff --git a/board/theobroma-systems/puma_rk3399/puma-rk3399.c b/board/theobroma-systems/puma_rk3399/puma-rk3399.c
index 27e3823..c6690fa 100644
--- a/board/theobroma-systems/puma_rk3399/puma-rk3399.c
+++ b/board/theobroma-systems/puma_rk3399/puma-rk3399.c
@@ -8,13 +8,17 @@
 #include <dm.h>
 #include <misc.h>
 #include <spl.h>
+#include <syscon.h>
 #include <usb.h>
 #include <dm/pinctrl.h>
 #include <dm/uclass-internal.h>
+#include <asm/io.h>
 #include <asm/gpio.h>
 #include <asm/setup.h>
 #include <asm/arch/clock.h>
 #include <asm/arch/cru_rk3399.h>
+#include <asm/arch/hardware.h>
+#include <asm/arch/grf_rk3399.h>
 #include <asm/arch/periph.h>
 #include <power/regulator.h>
 #include <u-boot/sha256.h>
@@ -180,10 +184,25 @@
 #endif
 }
 
+static void setup_iodomain(void)
+{
+	const u32 GRF_IO_VSEL_GPIO4CD_SHIFT = 3;
+	struct rk3399_grf_regs *grf =
+	    syscon_get_first_range(ROCKCHIP_SYSCON_GRF);
+
+	/*
+	 * Set bit 3 in GRF_IO_VSEL so PCIE_RST# works (pin GPIO4_C6).
+	 * Linux assumes that PCIE_RST# works out of the box as it probes
+	 * PCIe before loading the iodomain driver.
+	 */
+	rk_setreg(&grf->io_vsel, 1 << GRF_IO_VSEL_GPIO4CD_SHIFT);
+}
+
 int misc_init_r(void)
 {
 	setup_serial();
 	setup_macaddr();
+	setup_iodomain();
 
 	return 0;
 }
diff --git a/configs/evb-rk3399_defconfig b/configs/evb-rk3399_defconfig
index 7b5ea82..e8e52c3 100644
--- a/configs/evb-rk3399_defconfig
+++ b/configs/evb-rk3399_defconfig
@@ -4,6 +4,7 @@
 CONFIG_SPL_LIBGENERIC_SUPPORT=y
 CONFIG_SYS_MALLOC_F_LEN=0x4000
 CONFIG_ROCKCHIP_RK3399=y
+CONFIG_ROCKCHIP_SPL_RESERVE_IRAM=0x4000
 CONFIG_SPL_STACK_R_ADDR=0x80000
 CONFIG_DEFAULT_DEVICE_TREE="rk3399-evb"
 CONFIG_DEBUG_UART=y
diff --git a/configs/firefly-rk3399_defconfig b/configs/firefly-rk3399_defconfig
index 731222c..ab25015 100644
--- a/configs/firefly-rk3399_defconfig
+++ b/configs/firefly-rk3399_defconfig
@@ -4,11 +4,13 @@
 CONFIG_SPL_LIBGENERIC_SUPPORT=y
 CONFIG_SYS_MALLOC_F_LEN=0x4000
 CONFIG_ROCKCHIP_RK3399=y
+CONFIG_ROCKCHIP_SPL_RESERVE_IRAM=0x4000
 CONFIG_SPL_STACK_R_ADDR=0x80000
 CONFIG_DEFAULT_DEVICE_TREE="rk3399-firefly"
 CONFIG_DEBUG_UART=y
 CONFIG_FIT=y
 CONFIG_SPL_LOAD_FIT=y
+CONFIG_SPL_FIT_GENERATOR="arch/arm/mach-rockchip/make_fit_atf.py"
 # CONFIG_DISPLAY_CPUINFO is not set
 CONFIG_SPL_STACK_R=y
 CONFIG_SPL_STACK_R_MALLOC_SIMPLE_LEN=0x4000
diff --git a/env/Kconfig b/env/Kconfig
index 2477bf8..bef6e89 100644
--- a/env/Kconfig
+++ b/env/Kconfig
@@ -427,4 +427,22 @@
 
 endif
 
+if ARCH_ROCKCHIP
+
+config ENV_OFFSET
+	hex
+	depends on !ENV_IS_IN_UBI
+	depends on !ENV_IS_NOWHERE
+	default 0x3f8000
+	help
+	  Offset from the start of the device (or partition)
+
+config ENV_SIZE
+	hex
+	default 0x8000
+	help
+	  Size of the environment storage area
+
+endif
+
 endmenu
diff --git a/include/configs/puma_rk3399.h b/include/configs/puma_rk3399.h
index 39d0786..6523a7c 100644
--- a/include/configs/puma_rk3399.h
+++ b/include/configs/puma_rk3399.h
@@ -9,14 +9,6 @@
 
 #include <configs/rk3399_common.h>
 
-/*
- * SPL @ 32kB for ~130kB
- * ENV @ 240KB for 8kB
- * FIT payload (ATF, U-Boot, FDT) @ 256kB
- */
-#undef CONFIG_ENV_OFFSET
-#define CONFIG_ENV_OFFSET (240 * 1024)
-
 #if defined(CONFIG_ENV_IS_IN_MMC)
 #define CONFIG_SYS_MMC_ENV_DEV 1
 #elif defined(CONFIG_ENV_IS_IN_SPI_FLASH)
diff --git a/include/configs/rockchip-common.h b/include/configs/rockchip-common.h
index 35d948a..f465d35 100644
--- a/include/configs/rockchip-common.h
+++ b/include/configs/rockchip-common.h
@@ -52,21 +52,13 @@
 #define PARTS_DEFAULT \
 	"uuid_disk=${uuid_gpt_disk};" \
 	"name=loader1,start=32K,size=4000K,uuid=${uuid_gpt_loader1};" \
-	"name=reserved1,size=64K,uuid=${uuid_gpt_reserved1};" \
-	"name=reserved2,size=4M,uuid=${uuid_gpt_reserved2};" \
-	"name=loader2,size=4MB,uuid=${uuid_gpt_loader2};" \
-	"name=atf,size=4M,uuid=${uuid_gpt_atf};" \
+	"name=loader2,start=8MB,size=4MB,uuid=${uuid_gpt_loader2};" \
+	"name=trust,size=4M,uuid=${uuid_gpt_atf};" \
 	"name=boot,size=112M,bootable,uuid=${uuid_gpt_boot};" \
 	"name=rootfs,size=-,uuid="ROOT_UUID
 
 #endif
 
-/*
- * Rockchip SoCs use fixed ENV 32KB@(4MB-32KB)
- */
-#define CONFIG_ENV_OFFSET	(SZ_4M - SZ_32K)
-#define CONFIG_ENV_SIZE		SZ_32K
-
 #define CONFIG_DISPLAY_BOARDINFO_LATE
 
 #endif /* _ROCKCHIP_COMMON_H_ */