From d91e5532950c862f22bdae01d2e32777a44c3027 Mon Sep 17 00:00:00 2001
From: Ricardo Wurmus <rekado@elephly.net>
Date: Wed, 30 Mar 2022 22:38:58 +0200
Subject: [PATCH] WIP rockpro64 pcie u-boot

---
 gnu/local.mk                                  |   2 +
 gnu/packages/bootloaders.scm                  |  49 ++++++-
 .../u-boot-allow-disabling-openssl.patch      | 109 +++++---------
 .../patches/u-boot-rockchip-pcie-boot.patch   |  46 ++++++
 .../patches/u-boot-rockchip-pcie.patch        | 137 ++++++++++++++++++
 5 files changed, 268 insertions(+), 75 deletions(-)
 create mode 100644 gnu/packages/patches/u-boot-rockchip-pcie-boot.patch
 create mode 100644 gnu/packages/patches/u-boot-rockchip-pcie.patch

diff --git a/gnu/local.mk b/gnu/local.mk
index a704161abc..9de7c6b2a2 100644
--- a/gnu/local.mk
+++ b/gnu/local.mk
@@ -1869,6 +1869,8 @@ dist_patch_DATA =						\
   %D%/packages/patches/u-boot-allow-disabling-openssl.patch	\
   %D%/packages/patches/u-boot-nintendo-nes-serial.patch		\
   %D%/packages/patches/u-boot-rockchip-inno-usb.patch		\
+  %D%/packages/patches/u-boot-rockchip-pcie.patch		\
+  %D%/packages/patches/u-boot-rockchip-pcie-boot.patch		\
   %D%/packages/patches/u-boot-sifive-prevent-reloc-initrd-fdt.patch	\
   %D%/packages/patches/u-boot-riscv64-fix-extlinux.patch	\
   %D%/packages/patches/u-boot-rk3399-enable-emmc-phy.patch	\
diff --git a/gnu/packages/bootloaders.scm b/gnu/packages/bootloaders.scm
index 7987641031..320ae5bad6 100644
--- a/gnu/packages/bootloaders.scm
+++ b/gnu/packages/bootloaders.scm
@@ -498,6 +498,16 @@ (define %u-boot-rockchip-inno-usb-patch
   ;; and https://patchwork.ozlabs.org/project/uboot/patch/20210406151059.1187379-1-icenowy@aosc.io
   (search-patch "u-boot-rockchip-inno-usb.patch"))
 
+(define %u-boot-rockchip-pcie-patch
+  ;; Fixes error when enumerating PCIe devices.
+  ;; See https://github.com/NetBSD/pkgsrc/blob/trunk/sysutils/u-boot/patches-2022.01/patch-drivers_pci_pcie__rockchip.c
+  (search-patch "u-boot-rockchip-pcie.patch"))
+
+(define %u-boot-rockchip-pcie-boot-patch
+  ;; Fixes PCI config space handling.
+  ;; See https://github.com/NetBSD/pkgsrc/blob/trunk/sysutils/u-boot/patches-2022.01/patch-arch_arm_lib_interrupts__64.c
+  (search-patch "u-boot-rockchip-pcie-boot.patch"))
+
 (define %u-boot-sifive-prevent-relocating-initrd-fdt
   ;; Fix boot in 2021.07 on Hifive unmatched, see
   ;; https://bugs.launchpad.net/ubuntu/+source/u-boot/+bug/1937246
@@ -517,10 +527,12 @@ (define %u-boot-rk3399-enable-emmc-phy-patch
 (define u-boot
   (package
     (name "u-boot")
-    (version "2021.10")
+    (version "2022.01")
     (source (origin
 	      (patches
                (list %u-boot-rockchip-inno-usb-patch
+                     %u-boot-rockchip-pcie-patch
+                     %u-boot-rockchip-pcie-boot-patch
                      %u-boot-allow-disabling-openssl-patch
                      %u-boot-sifive-prevent-relocating-initrd-fdt
                      %u-boot-rk3399-enable-emmc-phy-patch))
@@ -530,7 +542,7 @@ (define u-boot
                     "u-boot-" version ".tar.bz2"))
               (sha256
                (base32
-                "1m0bvwv8r62s4wk4w3cmvs888dhv9gnfa98dczr4drk2jbhj7ryd"))))
+                "04q4d3yac8gp9q34dkjmcn7vpc0kr3dmvgx1z01qq8nv4wr59d41"))))
     (native-inputs
      `(("bc" ,bc)
        ("bison" ,bison)
@@ -986,6 +998,39 @@ (define-public u-boot-rockpro64-rk3399
                 (lambda* (#:key inputs #:allow-other-keys)
                   (setenv "BL31"
                           (search-input-file inputs "/bl31.elf"))))
+              ;; Add SCSI support to boot from SSD.
+              ;; See https://github.com/sigmaris/u-boot/commit/5a6b3285d1c6f659945eaf86989a7195a7f355ea
+              (add-after 'unpack 'patch-config
+                (lambda _
+                  (substitute* "configs/rockpro64-rk3399_defconfig"
+                    (("CONFIG_USB=y") "\
+CONFIG_USB=y
+CONFIG_AHCI=y
+CONFIG_AHCI_PCI=y
+CONFIG_SATA=y
+CONFIG_SATA_SIL=y
+CONFIG_SCSI=y
+CONFIG_SCSI_AHCI=y
+CONFIG_DM_SCSI=y
+"))
+                  (substitute* "include/config_distro_bootcmd.h"
+                    (("\"scsi_need_init=false")
+                     "\"setenv scsi_need_init false")
+                    (("#define BOOTENV_SET_SCSI_NEED_INIT \"scsi_need_init=;")
+                     "#define BOOTENV_SET_SCSI_NEED_INIT \"setenv scsi_need_init;"))
+                  (substitute* "include/configs/rockchip-common.h"
+                    (("#define BOOT_TARGET_DEVICES\\(func\\)")
+                     "
+#if CONFIG_IS_ENABLED(CMD_SCSI)
+	#define BOOT_TARGET_SCSI(func) func(SCSI, scsi, 0)
+#else
+	#define BOOT_TARGET_SCSI(func)
+#endif
+#define BOOT_TARGET_DEVICES(func)")
+                    (("BOOT_TARGET_NVME\\(func\\) \\\\")
+                     "\
+BOOT_TARGET_NVME(func) \\
+	BOOT_TARGET_SCSI(func) \\"))))
               ;; Phases do not succeed on the bl31 ELF.
               (delete 'strip)
               (delete 'validate-runpath)))))
diff --git a/gnu/packages/patches/u-boot-allow-disabling-openssl.patch b/gnu/packages/patches/u-boot-allow-disabling-openssl.patch
index e3ec92be84..98ab576b50 100644
--- a/gnu/packages/patches/u-boot-allow-disabling-openssl.patch
+++ b/gnu/packages/patches/u-boot-allow-disabling-openssl.patch
@@ -1,39 +1,6 @@
-From f060e90d148270307228315e2759a0065ec1d796 Mon Sep 17 00:00:00 2001
-From: Vagrant Cascadian <vagrant@debian.org>
-Date: Fri, 22 Oct 2021 17:34:53 -0700
-Subject: [PATCH] Revert "tools: kwbimage: Do not hide usage of secure header
- under CONFIG_ARMADA_38X"
-
-This reverts commit b4f3cc2c42d97967a3a3c8796c340f6b07ecccac.
----
- tools/Makefile   |  8 ++++++++
- tools/kwbimage.c | 22 ++++++++++++++++++++++
- 2 files changed, 30 insertions(+)
-
-diff --git a/tools/Makefile b/tools/Makefile
-index 4a86321f64..9517f203fd 100644
---- a/tools/Makefile
-+++ b/tools/Makefile
-@@ -169,6 +169,14 @@ HOST_EXTRACFLAGS	+= -DCONFIG_FIT_SIGNATURE_MAX_SIZE=0xffffffff
- HOST_EXTRACFLAGS	+= -DCONFIG_FIT_CIPHER
- endif
- 
-+ifneq ($(CONFIG_SYS_U_BOOT_OFFS),)
-+HOSTCFLAGS_kwbimage.o += -DCONFIG_SYS_U_BOOT_OFFS=$(CONFIG_SYS_U_BOOT_OFFS)
-+endif
-+
-+ifneq ($(CONFIG_ARMADA_38X),)
-+HOSTCFLAGS_kwbimage.o += -DCONFIG_KWB_SECURE
-+endif
-+
- # MXSImage needs LibSSL
- ifneq ($(CONFIG_MX23)$(CONFIG_MX28)$(CONFIG_ARMADA_38X)$(CONFIG_TOOLS_LIBCRYPTO),)
- HOSTCFLAGS_kwbimage.o += \
-diff --git a/tools/kwbimage.c b/tools/kwbimage.c
-index d200ff2425..23d6be3c9a 100644
---- a/tools/kwbimage.c
-+++ b/tools/kwbimage.c
-@@ -14,6 +14,7 @@
+--- a/tools/kwbimage.c	1970-01-01 01:00:01.000000000 +0100
++++ b/tools/kwbimage.c	2022-03-08 00:28:05.273754029 +0100
+@@ -17,6 +17,7 @@
  #include <stdint.h>
  #include "kwbimage.h"
  
@@ -41,7 +8,7 @@ index d200ff2425..23d6be3c9a 100644
  #include <openssl/bn.h>
  #include <openssl/rsa.h>
  #include <openssl/pem.h>
-@@ -39,10 +40,13 @@ void EVP_MD_CTX_cleanup(EVP_MD_CTX *ctx)
+@@ -42,10 +43,13 @@
  	EVP_MD_CTX_reset(ctx);
  }
  #endif
@@ -55,7 +22,7 @@ index d200ff2425..23d6be3c9a 100644
  
  struct boot_mode {
  	unsigned int id;
-@@ -237,6 +241,8 @@ image_count_options(unsigned int optiontype)
+@@ -246,6 +250,8 @@
  	return count;
  }
  
@@ -64,16 +31,15 @@ index d200ff2425..23d6be3c9a 100644
  static int image_get_csk_index(void)
  {
  	struct image_cfg_element *e;
-@@ -259,6 +265,8 @@ static bool image_get_spezialized_img(void)
- 	return e->sec_specialized_img;
- }
+@@ -256,6 +262,7 @@
  
+ 	return e->csk_idx;
+ }
 +#endif
-+
- /*
-  * Compute a 8-bit checksum of a memory area. This algorithm follows
-  * the requirements of the Marvell SoC BootROM specifications.
-@@ -353,6 +361,7 @@ static uint8_t baudrate_to_option(unsigned int baudrate)
+ 
+ static bool image_get_spezialized_img(void)
+ {
+@@ -366,6 +373,7 @@
  	}
  }
  
@@ -81,18 +47,17 @@ index d200ff2425..23d6be3c9a 100644
  static void kwb_msg(const char *fmt, ...)
  {
  	if (verbose_mode) {
-@@ -847,6 +856,8 @@ done:
+@@ -859,6 +867,7 @@
+ done:
  	return ret;
  }
- 
 +#endif
-+
- static void *image_create_v0(size_t *imagesz, struct image_tool_params *params,
- 			     int payloadsz)
+ 
+ static size_t image_headersz_align(size_t headersz, uint8_t blockid)
  {
-@@ -977,11 +988,13 @@ static size_t image_headersz_v1(int *hasext)
- 			*hasext = 1;
- 	}
+@@ -1003,11 +1012,13 @@
+ 	 */
+ 	headersz = sizeof(struct main_hdr_v1);
  
 +#if defined(CONFIG_KWB_SECURE)
  	if (image_get_csk_index() >= 0) {
@@ -102,18 +67,17 @@ index d200ff2425..23d6be3c9a 100644
  	}
 +#endif
  
- 	/*
- 	 * The payload should be aligned on some reasonable
-@@ -1058,6 +1071,8 @@ err_close:
+ 	count = image_count_options(IMAGE_CFG_DATA);
+ 	if (count > 0)
+@@ -1135,6 +1146,7 @@
  	return -1;
  }
  
 +#if defined(CONFIG_KWB_SECURE)
-+
  int export_pub_kak_hash(RSA *kak, struct secure_hdr_v1 *secure_hdr)
  {
  	FILE *hashf;
-@@ -1170,6 +1185,7 @@ int add_secure_header_v1(struct image_tool_params *params, uint8_t *ptr,
+@@ -1247,6 +1259,7 @@
  
  	return 0;
  }
@@ -121,17 +85,17 @@ index d200ff2425..23d6be3c9a 100644
  
  static void *image_create_v1(size_t *imagesz, struct image_tool_params *params,
  			     uint8_t *ptr, int payloadsz)
-@@ -1177,7 +1193,9 @@ static void *image_create_v1(size_t *imagesz, struct image_tool_params *params,
- 	struct image_cfg_element *e;
+@@ -1255,7 +1268,9 @@
  	struct main_hdr_v1 *main_hdr;
+ 	struct opt_hdr_v1 *ohdr;
  	struct register_set_hdr_v1 *register_set_hdr;
-+#if defined(CONFIG_KWB_SECURE)
++#if defined(CONFIG_KWB_SECURE)        
  	struct secure_hdr_v1 *secure_hdr = NULL;
-+#endif
++#endif        
  	size_t headersz;
  	uint8_t *image, *cur;
  	int hasext = 0;
-@@ -1253,6 +1271,7 @@ static void *image_create_v1(size_t *imagesz, struct image_tool_params *params,
+@@ -1339,6 +1354,7 @@
  	if (main_hdr->blockid == IBR_HDR_PEX_ID)
  		main_hdr->srcaddr = cpu_to_le32(0xFFFFFFFF);
  
@@ -139,26 +103,25 @@ index d200ff2425..23d6be3c9a 100644
  	if (image_get_csk_index() >= 0) {
  		/*
  		 * only reserve the space here; we fill the header later since
-@@ -1263,6 +1282,7 @@ static void *image_create_v1(size_t *imagesz, struct image_tool_params *params,
+@@ -1349,7 +1365,8 @@
  		*next_ext = 1;
  		next_ext = &secure_hdr->next;
  	}
+-
 +#endif
- 
++        
  	datai = 0;
  	register_set_hdr = (struct register_set_hdr_v1 *)cur;
-@@ -1310,9 +1330,11 @@ static void *image_create_v1(size_t *imagesz, struct image_tool_params *params,
+ 	for (cfgi = 0; cfgi < cfgn; cfgi++) {
+@@ -1396,9 +1413,11 @@
  			return NULL;
  	}
  
 +#if defined(CONFIG_KWB_SECURE)
- 	if (secure_hdr && add_secure_header_v1(params, ptr, payloadsz,
+ 	if (secure_hdr && add_secure_header_v1(params, ptr, payloadsz + headersz,
  					       headersz, image, secure_hdr))
  		return NULL;
 +#endif
  
- 	/* Calculate and set the header checksum */
- 	main_hdr->checksum = image_checksum8(main_hdr, headersz);
--- 
-2.30.2
-
+ 	*imagesz = headersz;
+ 
diff --git a/gnu/packages/patches/u-boot-rockchip-pcie-boot.patch b/gnu/packages/patches/u-boot-rockchip-pcie-boot.patch
new file mode 100644
index 0000000000..666d06b0ea
--- /dev/null
+++ b/gnu/packages/patches/u-boot-rockchip-pcie-boot.patch
@@ -0,0 +1,46 @@
+Taken from https://github.com/NetBSD/pkgsrc/raw/3b1d2f3d436b20a0755e5375594c2db36e947b95/sysutils/u-boot/patches-2022.01/patch-arch_arm_lib_interrupts__64.c
+
+$NetBSD: patch-arch_arm_lib_interrupts__64.c,v 1.1 2022/02/11 21:46:14 mrg Exp $
+
+u-boot-rockpro64: fix broken PCI config space handling:
+
+- Program bus number into the ECAM decoder for each access
+- Use type 1 PCI config cycles for config spaces behind bridge
+- Add a platform specific hack to the synchronous exception handler
+  to deal with PCI-e subsystem triggering data aborts when probing
+  nonexistent PCI devices.
+- properly delay after deasserting reset for downstream devices to
+  have time to initialize.
+
+Allows booting from PCI devices behind bridges and probing
+devices other than 0:0:0 and 1:0:0.
+
+--- a/arch/arm/lib/interrupts_64.c	2021-07-05 15:11:28.000000000 +0000
++++ b/arch/arm/lib/interrupts_64.c
+@@ -111,11 +111,26 @@ void do_bad_error(struct pt_regs *pt_reg
+ 	panic("Resetting CPU ...\n");
+ }
+ 
++#ifdef CONFIG_ROCKCHIP_RK3399
++extern volatile int rockchip_pcie_expect_data_abort;
++extern volatile int rockchip_pcie_got_data_abort;
++#endif
+ /*
+  * do_sync handles the Synchronous Abort exception.
+  */
+ void do_sync(struct pt_regs *pt_regs, unsigned int esr)
+ {
++#ifdef CONFIG_ROCKCHIP_RK3399
++	if ((esr >> 26) == 0x25 && rockchip_pcie_expect_data_abort) {
++		/*
++		 * Data Abort taken without a change in Exception level.
++		 * This happens when probing nonexistent PCI-e devices.
++		 */
++		rockchip_pcie_got_data_abort = 1;
++		pt_regs->elr += 4; /* skip faulting insn */
++		return;
++	}
++#endif
+ 	efi_restore_gd();
+ 	printf("\"Synchronous Abort\" handler, esr 0x%08x\n", esr);
+ 	show_regs(pt_regs);
diff --git a/gnu/packages/patches/u-boot-rockchip-pcie.patch b/gnu/packages/patches/u-boot-rockchip-pcie.patch
new file mode 100644
index 0000000000..ef123d25a2
--- /dev/null
+++ b/gnu/packages/patches/u-boot-rockchip-pcie.patch
@@ -0,0 +1,137 @@
+Taken from
+https://github.com/NetBSD/pkgsrc/raw/3b1d2f3d436b20a0755e5375594c2db36e947b95/sysutils/u-boot/patches-2022.01/patch-drivers_pci_pcie__rockchip.c
+
+$NetBSD: patch-drivers_pci_pcie__rockchip.c,v 1.1 2022/02/11 21:46:14 mrg Exp $
+
+u-boot-rockpro64: fix broken PCI config space handling:
+
+- Program bus number into the ECAM decoder for each access
+- Use type 1 PCI config cycles for config spaces behind bridge
+- Add a platform specific hack to the synchronous exception handler
+  to deal with PCI-e subsystem triggering data aborts when probing
+  nonexistent PCI devices.
+- properly delay after deasserting reset for downstream devices to
+  have time to initialize.
+
+Allows booting from PCI devices behind bridges and probing
+devices other than 0:0:0 and 1:0:0.
+
+--- a/drivers/pci/pcie_rockchip.c	2021-07-05 15:11:28.000000000 +0000
++++ b/drivers/pci/pcie_rockchip.c
+@@ -73,6 +73,8 @@ DECLARE_GLOBAL_DATA_PTR;
+ #define PCIE_ATR_OB_REGION0_SIZE	(32 * 1024 * 1024)
+ #define PCIE_ATR_OB_REGION_SIZE		(1 * 1024 * 1024)
+ 
++#define PCIE_ATR_REGION0_PASS_BITS (20 - 1)
++
+ struct rockchip_pcie {
+ 	fdt_addr_t axi_base;
+ 	fdt_addr_t apb_base;
+@@ -103,13 +105,15 @@ struct rockchip_pcie {
+ 
+ static int rockchip_pcie_off_conf(pci_dev_t bdf, uint offset)
+ {
+-	unsigned int bus = PCI_BUS(bdf);
+ 	unsigned int dev = PCI_DEV(bdf);
+ 	unsigned int func = PCI_FUNC(bdf);
+ 
+-	return (bus << 20) | (dev << 15) | (func << 12) | (offset & ~0x3);
++	return (dev << 15) | (func << 12) | (offset & ~0x3);
+ }
+ 
++volatile int rockchip_pcie_expect_data_abort;
++volatile int rockchip_pcie_got_data_abort;
++
+ static int rockchip_pcie_rd_conf(const struct udevice *udev, pci_dev_t bdf,
+ 				 uint offset, ulong *valuep,
+ 				 enum pci_size_t size)
+@@ -127,8 +131,33 @@ static int rockchip_pcie_rd_conf(const s
+ 	}
+ 
+ 	if ((bus == priv->first_busno + 1) && dev == 0) {
++		writel((bus << 20) | PCIE_ATR_REGION0_PASS_BITS,
++		       priv->apb_base + PCIE_ATR_OB_ADDR0(0));
++		writel(PCIE_ATR_HDR_CFG_TYPE0 | PCIE_ATR_HDR_RID,
++		       priv->apb_base + PCIE_ATR_OB_DESC0(0));
++		dsb();
+ 		value = readl(priv->axi_base + where);
+ 		*valuep = pci_conv_32_to_size(value, offset, size);
++		dsb();
++		return 0;
++	}
++
++	if (bus > priv->first_busno + 1) {
++		writel((bus << 20) | PCIE_ATR_REGION0_PASS_BITS,
++		       priv->apb_base + PCIE_ATR_OB_ADDR0(0));
++		writel(PCIE_ATR_HDR_CFG_TYPE1 | PCIE_ATR_HDR_RID,
++		       priv->apb_base + PCIE_ATR_OB_DESC0(0));
++		dsb();
++		rockchip_pcie_got_data_abort = 0;
++		rockchip_pcie_expect_data_abort = 1;
++		value = readl(priv->axi_base + where);
++		rockchip_pcie_expect_data_abort = 0;
++		if (rockchip_pcie_got_data_abort) {
++			*valuep = pci_get_ff(size);
++			return 0;
++		}
++		*valuep = pci_conv_32_to_size(value, offset, size);
++		dsb();
+ 		return 0;
+ 	}
+ 
+@@ -155,9 +184,28 @@ static int rockchip_pcie_wr_conf(struct 
+ 	}
+ 
+ 	if ((bus == priv->first_busno + 1) && dev == 0) {
++		writel((bus << 20) | PCIE_ATR_REGION0_PASS_BITS,
++		       priv->apb_base + PCIE_ATR_OB_ADDR0(0));
++		writel(PCIE_ATR_HDR_CFG_TYPE0 | PCIE_ATR_HDR_RID,
++		       priv->apb_base + PCIE_ATR_OB_DESC0(0));
++		dsb();
+ 		old = readl(priv->axi_base + where);
+ 		value = pci_conv_size_to_32(old, value, offset, size);
+ 		writel(value, priv->axi_base + where);
++		dsb();
++		return 0;
++	}
++
++	if (bus > priv->first_busno + 1) {
++		writel((bus << 20) | PCIE_ATR_REGION0_PASS_BITS,
++		       priv->apb_base + PCIE_ATR_OB_ADDR0(0));
++		writel(PCIE_ATR_HDR_CFG_TYPE1 | PCIE_ATR_HDR_RID,
++		       priv->apb_base + PCIE_ATR_OB_DESC0(0));
++		dsb();
++		old = readl(priv->axi_base + where);
++		value = pci_conv_size_to_32(old, value, offset, size);
++		writel(value, priv->axi_base + where);
++		dsb();
+ 		return 0;
+ 	}
+ 
+@@ -173,7 +221,7 @@ static int rockchip_pcie_atr_init(struct
+ 	int i, region;
+ 
+ 	/* Use region 0 to map PCI configuration space. */
+-	writel(25 - 1, priv->apb_base + PCIE_ATR_OB_ADDR0(0));
++	writel(PCIE_ATR_REGION0_PASS_BITS, priv->apb_base + PCIE_ATR_OB_ADDR0(0));
+ 	writel(0, priv->apb_base + PCIE_ATR_OB_ADDR1(0));
+ 	writel(PCIE_ATR_HDR_CFG_TYPE0 | PCIE_ATR_HDR_RID,
+ 	       priv->apb_base + PCIE_ATR_OB_DESC0(0));
+@@ -343,6 +391,8 @@ static int rockchip_pcie_init_port(struc
+ 		goto err_power_off_phy;
+ 	}
+ 
++	mdelay(20);	/* 20 ms according to PCI-e BS "Conventional Reset" */
++
+ 	/* Enable Gen1 training */
+ 	writel(PCIE_CLIENT_LINK_TRAIN_ENABLE,
+ 	       priv->apb_base + PCIE_CLIENT_CONFIG);
+@@ -378,6 +428,8 @@ static int rockchip_pcie_init_port(struc
+ 		goto err_power_off_phy;
+ 	}
+ 
++	mdelay(80);   /* wait 100 ms before CSR accesses. Already waited 20. */
++
+ 	return 0;
+ 
+ err_power_off_phy:
-- 
2.34.0

