liuyq / android-issues

place to write notes about investigation on android issues
0 stars 0 forks source link

firmware-hikey960 - serial number was changed to 96Boards for some reason #10

Open liuyq opened 2 years ago

liuyq commented 2 years ago

prebuilt firmwares: https://snapshots.linaro.org/reference-platform/components/uefi-staging/114/hikey960/debug/ http://snapshots.linaro.org/reference-platform/components/uefi-staging/114/hikey960/release/ https://ci.linaro.org/job/96boards-reference-uefi-staging/ https://git.linaro.org/ci/job/configs.git/tree/96boards-reference-uefi-staging.yaml https://git.linaro.org/ci/job/configs.git/tree/rpb-uefi/staging/builders.sh

Repositories: https://github.com/96boards-hikey/edk2 testing/hikey960_v2.5 https://github.com/96boards-hikey/l-loader testing/hikey960_v1.2 https://github.com/96boards-hikey/OpenPlatformPkg testing/hikey960_v1.3.4 https://github.com/OP-TEE/optee_os.git 3.0.0 https://github.com/96boards-hikey/tools-images-hikey960.git master https://git.trustedfirmware.org/TF-A/trusted-firmware-a.git integration https://git.linaro.org/uefi/uefi-tools.git master

Build instructions: https://git.linaro.org/ci/job/configs.git/tree/rpb-uefi/staging/builders.sh l-loader/build_uefi.sh https://github.com/johnstultz-work/dockerstuff/blob/master/Dockerfile.uefi960 https://github.com/96boards-hikey/l-loader/blob/testing/hikey960_v1.2/generate_ptable.sh

Lab Instructions: https://linaro.atlassian.net/wiki/spaces/CTT/pages/25118245487/Hikey+960

output:

$ fastboot oem serialno set 765ECF4C0225A895
...
FAILED (remote: Error while executing command)
$
$ fastboot devices
96Boards    fastboot
$
$ dmesg
[Tue Apr 26 12:49:26 2022] usb 2-1.5.3.4: New USB device found, idVendor=18d1, idProduct=d00d, bcdDevice= 1.00
[Tue Apr 26 12:49:26 2022] usb 2-1.5.3.4: New USB device strings: Mfr=1, Product=2, SerialNumber=3
[Tue Apr 26 12:49:26 2022] usb 2-1.5.3.4: Product: HiKey960
[Tue Apr 26 12:49:26 2022] usb 2-1.5.3.4: Manufacturer: 96Boards
[Tue Apr 26 12:49:26 2022] usb 2-1.5.3.4: SerialNumber: 96Boards
[Tue Apr 26 12:51:36 2022] usb 2-1.5.3.3: USB disconnect, device number 111
$

https://discuss.96boards.org/t/synchronous-exception-at-0x0000000000000000-while-flashing-prm-ptable-img/6565/9 https://github.com/96boards-hikey/tools-images-hikey960/issues/33

$fastboot -s 96Boards flash ptable prm_ptable.img -S 256M
Downloading 24576 bytes
     512 /    24576 bytes downloaded (2%) 
 16896 /    24576 bytes downloaded (68%)
 24576 /    24576 bytes downloaded (100%)
Flashing partition ptable 
Synchronous Exception at 0x0000000000000000
$
Downloading 1666048 bytes
        512 /  1666048 bytes downloaded (0%)
1583616 /  1666048 bytes downloaded (95%) 
1600000 /  1666048 bytes downloaded (96%) 
1616384 /  1666048 bytes downloaded (97%)
1632768 /  1666048 bytes downloaded (98%)
1649152 /  1666048 bytes downloaded (98%)
1665536 /  1666048 bytes downloaded (99%)
1666048 /  1666048 bytes downloaded (100%)
Flashing partition fip
No such partition.
$
Downloading 154752 bytes
      512 /   154752 bytes downloaded (0%)
147456 /   154752 bytes downloaded (95%) 
154752 /   154752 bytes downloaded (100%)
Flashing partition xloader
No such partition.
$

This problem seems to be caused with the "TOSHIBA THGBF7G8K4LBATRC 0100 PQ" ufs chip, but not sure why it works first, and then failed after some times, but still could be recovered from the recover mode many issues reported on it:

there 3 ufs types for hikey960

liuyq commented 2 years ago

./OpenPlatformPkg/Library/UsbSerialNumberLib/UsbSerialNumberLib.c

EFI_STATUS
LoadSNFromBlock (
  IN  EFI_HANDLE              FlashHandle,
  IN  EFI_LBA                 Lba,
  OUT CHAR16                 *UnicodeSN
  )
{
  EFI_STATUS                  Status;
  EFI_BLOCK_IO_PROTOCOL      *BlockIoProtocol;
  VOID                       *DataPtr;
  BOOLEAN                     Found = FALSE;
  UINT32                      Seed;
  RANDOM_SERIAL_NUMBER       *RandomSN;
  UINTN                       NumPages;
  CHAR16                      UnicodeStr[SERIAL_NUMBER_SIZE];

  if (UnicodeSN == NULL) {
    return EFI_INVALID_PARAMETER;
  }
  Status = gBS->OpenProtocol (
                  FlashHandle,
                  &gEfiBlockIoProtocolGuid,
                  (VOID **) &BlockIoProtocol,
                  gImageHandle,
                  NULL,
                  EFI_OPEN_PROTOCOL_GET_PROTOCOL
                  );
  if (EFI_ERROR (Status)) {
    DEBUG ((DEBUG_WARN, "Warning: Couldn't open block device (status: %r)\n", Status));
    return EFI_DEVICE_ERROR;
  }

  NumPages = EFI_SIZE_TO_PAGES (BlockIoProtocol->Media->BlockSize);
  DataPtr = AllocatePages (NumPages);
  if (DataPtr == NULL) {
    return EFI_BUFFER_TOO_SMALL;
  }
  Status = BlockIoProtocol->ReadBlocks (
                              BlockIoProtocol,
                              BlockIoProtocol->Media->MediaId,
                              Lba,
                              BlockIoProtocol->Media->BlockSize,
                              DataPtr
                              );
  if (EFI_ERROR (Status)) {
    DEBUG ((DEBUG_WARN, "Warning: Failed on reading blocks\n"));
    goto Exit;
  }

  Seed = ArmGenericTimerGetSystemCount ();
  RandomSN = (RANDOM_SERIAL_NUMBER *)DataPtr;
  if (RandomSN->Magic == RANDOM_MAGIC) {
    Found = TRUE;
    // Verify the unicode string.
    ZeroMem (UnicodeStr, SERIAL_NUMBER_SIZE * sizeof (CHAR16));
    UnicodeSPrint (UnicodeStr, SERIAL_NUMBER_SIZE * sizeof (CHAR16), L"%lx", RandomSN->Data);
    if (StrLen (RandomSN->UnicodeSN) != StrLen (UnicodeStr)) {
      Found = FALSE;
    }
    if (StrnCmp (RandomSN->UnicodeSN, UnicodeStr, StrLen (UnicodeStr)) != 0) {
      Found = FALSE;
    }
  }
  if (Found == FALSE) {
    Status = GenerateUsbSNBySeed (Seed, RandomSN);
    if (EFI_ERROR (Status)) {
      DEBUG ((DEBUG_WARN, "Warning: Failed to generate serial number\n"));
      goto Exit;
    }
    // Update SN to block device
    Status = BlockIoProtocol->WriteBlocks (
                                BlockIoProtocol,
                                BlockIoProtocol->Media->MediaId,
                                Lba,
                                BlockIoProtocol->Media->BlockSize,
                                DataPtr
                                );
    if (EFI_ERROR (Status)) {
      DEBUG ((DEBUG_WARN, "Warning: Failed on writing blocks\n"));
      goto Exit;
    }
  }
  CopyMem (UnicodeSN, RandomSN->UnicodeSN, SERIAL_NUMBER_SIZE * sizeof (CHAR16));
Exit:
  FreePages (DataPtr, NumPages);
  return Status;
}

./OpenPlatformPkg/Platforms/Hisilicon/HiKey960/HiKey960FastbootDxe/HiKey960FastbootDxe.c:567:

EFI_STATUS
HiKey960FastbootPlatformGetVar (
  IN  CHAR8   *Name,
  OUT CHAR8   *Value
  )
{
  EFI_STATUS               Status = EFI_SUCCESS;
  UINT64                   PartitionSize;
  FASTBOOT_PARTITION_LIST *Entry;
  CHAR16                   PartitionNameUnicode[60];
  BOOLEAN                  PartitionFound;
  CHAR16                   UnicodeSN[SERIAL_NUMBER_SIZE];

  if (!AsciiStrCmp (Name, "max-download-size")) {
    AsciiStrCpy (Value, FixedPcdGetPtr (PcdArmFastbootFlashLimit));
  } else if (!AsciiStrCmp (Name, "product")) {
    AsciiStrCpy (Value, FixedPcdGetPtr (PcdFirmwareVendor));
  } else if (!AsciiStrCmp (Name, "serialno")) {
    Status = LoadSNFromBlock (mFlashHandle, SERIAL_NUMBER_LBA, UnicodeSN);
    UnicodeStrToAsciiStr (UnicodeSN, Value);
  } else if ( !AsciiStrnCmp (Name, "partition-size", 14)) {
    AsciiStrToUnicodeStr ((Name + 15), PartitionNameUnicode);
    PartitionFound = FALSE;
    Entry = (FASTBOOT_PARTITION_LIST *) GetFirstNode (&(mPartitionListHead));
    while (!IsNull (&mPartitionListHead, &Entry->Link)) {
      // Search the partition list for the partition named by PartitionName
      if (StrCmp (Entry->PartitionName, PartitionNameUnicode) == 0) {
        PartitionFound = TRUE;
        break;
      }

     Entry = (FASTBOOT_PARTITION_LIST *) GetNextNode (&mPartitionListHead, &(Entry)->Link);
    }
    if (!PartitionFound) {
      *Value = '\0';
      return EFI_NOT_FOUND;
    }

    PartitionSize = (Entry->EndingLBA - Entry->StartingLBA + 1) * mFlashBlockIo->Media->BlockSize;
    DEBUG ((DEBUG_ERROR, "Fastboot platform: check for partition-size:%a 0X%llx\n", Name, PartitionSize ));
    AsciiSPrint (Value, 12, "0x%llx", PartitionSize);
  } else if ( !AsciiStrnCmp (Name, "partition-type", 14)) {
      DEBUG ((DEBUG_ERROR, "Fastboot platform: check for partition-type:%a\n", (Name + 15) ));
    if ( !AsciiStrnCmp  ( (Name + 15) , "system", 6) || !AsciiStrnCmp  ( (Name + 15) , "userdata", 8)
            || !AsciiStrnCmp  ( (Name + 15) , "cache", 5)) {
      AsciiStrCpy (Value, "ext4");
    } else {
      AsciiStrCpy (Value, "raw");
    }
  } else if ( !AsciiStrCmp (Name, "erase-block-size")) {
    AsciiSPrint (Value, 12, "0x%llx", UFS_BLOCK_SIZE);
  } else if ( !AsciiStrCmp (Name, "logical-block-size")) {
    AsciiSPrint (Value, 12, "0x%llx", UFS_BLOCK_SIZE);
  } else { 
    *Value = '\0';
  }
  return Status;
}

EFI_STATUS
HiKey960FastbootPlatformOemCommand (
  IN  CHAR8   *Command
  )
{
  EFI_STATUS   Status;
  CHAR16       UnicodeSN[SERIAL_NUMBER_SIZE];
  UINTN        Size;

  Size = AsciiStrLen ("serialno");
  if (AsciiStrCmp (Command, "Demonstrate") == 0) {
    DEBUG ((DEBUG_ERROR, "ARM OEM Fastboot command 'Demonstrate' received.\n"));
    return EFI_SUCCESS;
  } else if (AsciiStrnCmp (Command, "serialno", Size) == 0) {
    while (*(Command + Size) == ' ') {
      Size++;
    }   
    if (AsciiStrnCmp (Command + Size, "set", AsciiStrLen ("set")) == 0) {
      Size += AsciiStrLen ("set");
      while (*(Command + Size) == ' ') {
        Size++;
      }   
      Status = AssignUsbSN (Command + Size, UnicodeSN);
      if (EFI_ERROR (Status)) {
        DEBUG ((DEBUG_ERROR, "Failed to set USB Serial Number.\n"));
        return Status;
      }   
    } else {
      Status = GenerateUsbSN (UnicodeSN);
      if (EFI_ERROR (Status)) {
        DEBUG ((DEBUG_ERROR, "Failed to generate USB Serial Number.\n"));
        return Status;
      }   
    }   
    Status = StoreSNToBlock (mFlashHandle, SERIAL_NUMBER_LBA, UnicodeSN);
    return Status;
  } else if (AsciiStrCmp (Command, "reboot-bootloader") == 0) {
    MmioWrite32 (ADB_REBOOT_ADDRESS, ADB_REBOOT_BOOTLOADER);
    WriteBackInvalidateDataCacheRange ((VOID *)ADB_REBOOT_ADDRESS, 4); 
    return EFI_SUCCESS;
  } else {
    DEBUG ((DEBUG_ERROR,
      "HiKey960: Unrecognised Fastboot OEM command: %a\n",
      Command
      )); 
    return EFI_NOT_FOUND;
  }
}

./OpenPlatformPkg/Platforms/Hisilicon/HiKey960/HiKey960UsbDxe/HiKey960UsbDxe.c

EFI_STATUS
EFIAPI
HiKey960UsbGetSerialNo (
  OUT CHAR16            *SerialNo,
  OUT UINT8             *Length
  )
{
  EFI_STATUS                          Status;
  EFI_DEVICE_PATH_PROTOCOL           *FlashDevicePath;

  if (mFlashHandle == 0) {
    FlashDevicePath = ConvertTextToDevicePath ((CHAR16*)FixedPcdGetPtr (PcdAndroidFastbootNvmDevicePath));
    Status = gBS->LocateDevicePath (&gEfiBlockIoProtocolGuid, &FlashDevicePath, &mFlashHandle);
    if (EFI_ERROR (Status)) {
      DEBUG ((DEBUG_ERROR, "Warning: Couldn't locate Android NVM device (status: %r)\n", Status));
      // Failing to locate partitions should not prevent to do other Android FastBoot actions
      return EFI_SUCCESS;
    }   
  }

  if ((SerialNo == NULL) || (Length == NULL)) {
    return EFI_INVALID_PARAMETER;
  }
  Status = LoadSNFromBlock (mFlashHandle, SERIAL_NUMBER_LBA, SerialNo);
  *Length = StrSize (SerialNo);
  return Status;
}
liuyq commented 2 years ago

https://android.googlesource.com/device/linaro/hikey/+/refs/heads/master/installer/hikey960/flash-all.sh

function flashing_atf_uefi () {
    fastboot flash ptable prm_ptable.img
    fastboot flash xloader hisi-sec_xloader.img
    fastboot reboot-bootloader

    fastboot flash fastboot l-loader.bin
    fastboot flash fip fip.bin
    fastboot flash nvme hisi-nvme.img
    fastboot flash fw_lpm3 hisi-lpm3.img
    fastboot flash trustfirmware hisi-bl31.bin
    fastboot reboot-bootloader

    fastboot flash ptable prm_ptable.img
    fastboot flash xloader hisi-sec_xloader.img
    fastboot flash fastboot l-loader.bin
    fastboot flash fip fip.bin

    fastboot flash boot "${ANDROID_PRODUCT_OUT}"/boot.img
    fastboot flash super "${ANDROID_PRODUCT_OUT}"/super.img
    fastboot flash userdata "${ANDROID_PRODUCT_OUT}"/userdata.img
    fastboot format cache
}

https://github.com/96boards-hikey/l-loader/blob/testing/hikey960_v1.2/hikey960.mk

BL1=bl1.bin
BL2=bl2.bin
NS_BL1U=BL33_AP_UEFI.fd
PTABLE_LST:=aosp-32g aosp-32g-spare linux-32g

.PHONY: all 
all: l-loader.bin prm_ptable.img recovery.bin

l-loader.bin: $(BL2)
    cp -f $(BL2) l-loader.bin

prm_ptable.img:
    for ptable in $(PTABLE_LST); do \
        PTABLE=$${ptable} SECTOR_SIZE=4096 SGDISK=./sgdisk bash -x generate_ptable.sh;\
        cp prm_ptable.img ptable-$${ptable}.img;\
    done

recovery.bin: $(BL1) $(NS_BL1U)
    python gen_loader_hikey960.py -o $@ --img_bl1=$(BL1) --img_ns_bl1u=$(NS_BL1U)

.PHONY: clean
clean:
    rm -f prm_ptable.img l-loader.bin recovery.bin
liuyq commented 2 years ago

https://review.trustedfirmware.org/plugins/gitiles/OP-TEE/build/+/1e8d0b5a2b383834d09e3dfc5a9216fcef557a24%5E%21/#F0 build instruction and files generated for the firmware:

11:38:02 P15v:l-loader$ GENERATE_PTABLE=1 ./build_uefi.sh hikey960
11:38:34 P15v:uefi-hikey960$ find ./     -name prm_ptable.img     -o -name hisi-sec_xloader.img     -o -name l-loader.bin     -o -name fip.bin     -o -name hisi-nvme.img     -o -name hisi-lpm3.img     -o -name hisi-bl31.bin
./OpenPlatformPkg/Platforms/Hisilicon/Binary/D05/fip.bin
./OpenPlatformPkg/Platforms/Hisilicon/Binary/D02/fip.bin
./OpenPlatformPkg/Platforms/Hisilicon/Binary/D03/fip.bin
./arm-trusted-firmware/build/hikey960/debug/fip.bin
./l-loader/fip.bin
./l-loader/prm_ptable.img
./l-loader/l-loader.bin
./tools-images-hikey960/hisi-lpm3.img
./tools-images-hikey960/hisi-bl31.bin
./tools-images-hikey960/hisi-sec_xloader.img
./tools-images-hikey960/hisi-nvme.img
11:38:38 P15v:uefi-hikey960$ ll ./arm-trusted-firmware/build/hikey960/debug/fip.bin ./l-loader/fip.bin
-rw-rw-r-- 1 liuyq liuyq 1666048 5月   6 11:37 ./arm-trusted-firmware/build/hikey960/debug/fip.bin
lrwxrwxrwx 1 liuyq liuyq      52 5月   6 11:37 ./l-loader/fip.bin -> ../arm-trusted-firmware/build/hikey960/debug/fip.bin
11:38:41 P15v:uefi-hikey960$
10:59:39 P15v:uefi-hikey960$ ./arm-trusted-firmware/tools/fiptool/fiptool info l-loader/fip.bin 
SCP Firmware SCP_BL2: offset=0x200, size=0x35088, cmdline="--scp-fw"
EL3 Runtime Firmware BL31: offset=0x35400, size=0xD021, cmdline="--soc-fw"
Secure Payload BL32 (Trusted OS): offset=0x42600, size=0x1C, cmdline="--tos-fw"
Secure Payload BL32 Extra1 (Trusted OS Extra1): offset=0x42800, size=0x64280, cmdline="--tos-fw-extra1"
Non-Trusted Firmware BL33: offset=0xA6C00, size=0xF0000, cmdline="--nt-fw"
10:59:49 P15v:uefi-hikey960$ 

firmware memory layouts are defined here: arm-trusted-firmware/plat/hisilicon/hikey960/

liuyq commented 2 years ago

../edk2/MdePkg/Include/Protocol/DevicePath.h

/**
  This protocol can be used on any device handle to obtain generic path/location 
  information concerning the physical device or logical device. If the handle does 
  not logically map to a physical device, the handle may not necessarily support 
  the device path protocol. The device path describes the location of the device 
  the handle is for. The size of the Device Path can be determined from the structures 
  that make up the Device Path.
**/
typedef struct {
  UINT8 Type;       ///< 0x01 Hardware Device Path.
                    ///< 0x02 ACPI Device Path.
                    ///< 0x03 Messaging Device Path.
                    ///< 0x04 Media Device Path.
                    ///< 0x05 BIOS Boot Specification Device Path.
                    ///< 0x7F End of Hardware Device Path.

  UINT8 SubType;    ///< Varies by Type
                    ///< 0xFF End Entire Device Path, or
                    ///< 0x01 End This Instance of a Device Path and start a new
                    ///< Device Path.

  UINT8 Length[2];  ///< Specific Device Path data. Type and Sub-Type define
                    ///< type of data. Size of data is included in Length.

} EFI_DEVICE_PATH_PROTOCOL;

edk2/MdePkg/Include/Protocol/BlockIo.h

struct _EFI_BLOCK_IO_PROTOCOL {
  /// 
  /// The revision to which the block IO interface adheres. All future
  /// revisions must be backwards compatible. If a future version is not
  /// back wards compatible, it is not the same GUID.
  /// 
  UINT64              Revision;
  /// 
  /// Pointer to the EFI_BLOCK_IO_MEDIA data for this device.
  /// 
  EFI_BLOCK_IO_MEDIA  *Media;

  EFI_BLOCK_RESET     Reset;
  EFI_BLOCK_READ      ReadBlocks;
  EFI_BLOCK_WRITE     WriteBlocks;
  EFI_BLOCK_FLUSH     FlushBlocks;

};

extern EFI_GUID gEfiBlockIoProtocolGuid;
liuyq commented 2 years ago
diff --git a/Drivers/Usb/DwUsb3Dxe/DwUsb3Dxe.c b/Drivers/Usb/DwUsb3Dxe/DwUsb3Dxe.c
index 408d744..a9f83d3 100644
--- a/Drivers/Usb/DwUsb3Dxe/DwUsb3Dxe.c
+++ b/Drivers/Usb/DwUsb3Dxe/DwUsb3Dxe.c
@@ -1932,7 +1932,9 @@ DwUsb3DoGetDescriptor (
         ASSERT (Descriptor != NULL);
         Descriptor->Length = SERIAL_STRING_LENGTH * sizeof (CHAR16);
         Descriptor->DescriptorType = USB_DESC_TYPE_STRING;
+        DEBUG ((DEBUG_ERROR, "#%a, %d: UDESC_STRING: STRING_SERIAL: before call DwUsb->GetSerialN\n", __func__, __LINE__));
         DwUsb->GetSerialNo (Descriptor->String, &Descriptor->Length);
+        DEBUG ((DEBUG_ERROR, "#%a, %d: UDESC_STRING: STRING_SERIAL: after call DwUsb->GetSerialN\n", __func__, __LINE__));
         value = Descriptor->Length;
         break;
       default:
diff --git a/Library/UsbSerialNumberLib/UsbSerialNumberLib.c b/Library/UsbSerialNumberLib/UsbSerialNumberLib.c
index 550a973..caa3444 100644
--- a/Library/UsbSerialNumberLib/UsbSerialNumberLib.c
+++ b/Library/UsbSerialNumberLib/UsbSerialNumberLib.c
@@ -156,9 +156,12 @@ LoadSNFromBlock (
   UINTN                       NumPages;
   CHAR16                      UnicodeStr[SERIAL_NUMBER_SIZE];

+  DEBUG ((DEBUG_ERROR, "#%a, %d\n", __func__, __LINE__));
   if (UnicodeSN == NULL) {
+    DEBUG ((DEBUG_ERROR, "#%a, %d UnicodeSN is null\n", __func__, __LINE__));
     return EFI_INVALID_PARAMETER;
   }
+  DEBUG ((DEBUG_ERROR, "#%a, %d before call gBS->OpenProtocol\n", __func__, __LINE__));
   Status = gBS->OpenProtocol (
                   FlashHandle,
                   &gEfiBlockIoProtocolGuid,
@@ -168,13 +171,14 @@ LoadSNFromBlock (
                   EFI_OPEN_PROTOCOL_GET_PROTOCOL
                   );
   if (EFI_ERROR (Status)) {
-    DEBUG ((DEBUG_WARN, "Warning: Couldn't open block device (status: %r)\n", Status));
+    DEBUG ((DEBUG_ERROR, "#%a, %d Warning: Couldn't open block device (status: %r)\n",  __func__, __LINE__, Status));
     return EFI_DEVICE_ERROR;
   }

   NumPages = EFI_SIZE_TO_PAGES (BlockIoProtocol->Media->BlockSize);
   DataPtr = AllocatePages (NumPages);
   if (DataPtr == NULL) {
+    DEBUG ((DEBUG_ERROR, "#%a, %d Warning: EFI_BUFFER_TOO_SMALL\n", __func__, __LINE__));
     return EFI_BUFFER_TOO_SMALL;
   }
   Status = BlockIoProtocol->ReadBlocks (
@@ -185,7 +189,7 @@ LoadSNFromBlock (
                               DataPtr
                               );
   if (EFI_ERROR (Status)) {
-    DEBUG ((DEBUG_WARN, "Warning: Failed on reading blocks\n"));
+    DEBUG ((DEBUG_ERROR, "#%a, %d Warning: Failed on reading blocks (status: %r)\n",  __func__, __LINE__, Status));
     goto Exit;
   }

@@ -194,6 +198,7 @@ LoadSNFromBlock (
   if (RandomSN->Magic == RANDOM_MAGIC) {
     Found = TRUE;
     // Verify the unicode string.
+    DEBUG ((DEBUG_ERROR, "#%a, %d Info: found RandomSN, try Verify the unicode string\n", __func__, __LINE__));
     ZeroMem (UnicodeStr, SERIAL_NUMBER_SIZE * sizeof (CHAR16));
     UnicodeSPrint (UnicodeStr, SERIAL_NUMBER_SIZE * sizeof (CHAR16), L"%lx", RandomSN->Data);
     if (StrLen (RandomSN->UnicodeSN) != StrLen (UnicodeStr)) {
@@ -204,9 +209,10 @@ LoadSNFromBlock (
     }
   }
   if (Found == FALSE) {
+    DEBUG ((DEBUG_ERROR, "#%a, %d Info: not found RandomSN, try GenerateUsbSNBySeed\n", __func__, __LINE__));
     Status = GenerateUsbSNBySeed (Seed, RandomSN);
     if (EFI_ERROR (Status)) {
-      DEBUG ((DEBUG_WARN, "Warning: Failed to generate serial number\n"));
+      DEBUG ((DEBUG_ERROR, "#%a, %d Warning: Failed to generate serial number (status: %r)\n", __func__, __LINE__, Status));
       goto Exit;
     }
     // Update SN to block device
@@ -218,11 +224,12 @@ LoadSNFromBlock (
                                 DataPtr
                                 );
     if (EFI_ERROR (Status)) {
-      DEBUG ((DEBUG_WARN, "Warning: Failed on writing blocks\n"));
+      DEBUG ((DEBUG_WARN, "#%a, %d Warning: Failed on writing blocks (status: %r)\n",  __func__, __LINE__, Status));
       goto Exit;
     }
   }
   CopyMem (UnicodeSN, RandomSN->UnicodeSN, SERIAL_NUMBER_SIZE * sizeof (CHAR16));
+  DEBUG ((DEBUG_ERROR, "#%a, %d, RandomSN->UnicodeSN=%s, UnicodeStr=%s\n", __func__, __LINE__, RandomSN->UnicodeSN, UnicodeStr));
 Exit:
   FreePages (DataPtr, NumPages);
   return Status;
diff --git a/Platforms/Hisilicon/HiKey960/HiKey960UsbDxe/HiKey960UsbDxe.c b/Platforms/Hisilicon/HiKey960/HiKey960UsbDxe/HiKey960UsbDxe.c
index 8a771b6..7748f0e 100644
--- a/Platforms/Hisilicon/HiKey960/HiKey960UsbDxe/HiKey960UsbDxe.c
+++ b/Platforms/Hisilicon/HiKey960/HiKey960UsbDxe/HiKey960UsbDxe.c
@@ -321,21 +321,29 @@ HiKey960UsbGetSerialNo (
   EFI_STATUS                          Status;
   EFI_DEVICE_PATH_PROTOCOL           *FlashDevicePath;

+  DEBUG ((DEBUG_ERROR, "#%a, %d: debug for HiKey960UsbGetSerialNo start\n", __func__, __LINE__));
   if (mFlashHandle == 0) {
     FlashDevicePath = ConvertTextToDevicePath ((CHAR16*)FixedPcdGetPtr (PcdAndroidFastbootNvmDevicePath));
+    DEBUG ((DEBUG_ERROR, "#%a, %d, mFlashHandle == 0, TextToDevicePath=%s\n", __func__, __LINE__, (CHAR16*)FixedPcdGetPtr (PcdAndroidFastbootNvmDevicePath)));
+    if ( FlashDevicePath == NULL ) {
+      DEBUG ((DEBUG_ERROR, "#%a, %d, mFlashHandle == 0, FlashDevicePath == NULL\n", __func__, __LINE__));
+    }
     Status = gBS->LocateDevicePath (&gEfiBlockIoProtocolGuid, &FlashDevicePath, &mFlashHandle);
     if (EFI_ERROR (Status)) {
-      DEBUG ((DEBUG_ERROR, "Warning: Couldn't locate Android NVM device (status: %r)\n", Status));
+      DEBUG ((DEBUG_ERROR, "#%a, %d: Warning: Couldn't locate Android NVM device (status: %r)\n", __func__, __LINE__, Status));
       // Failing to locate partitions should not prevent to do other Android FastBoot actions
       return EFI_SUCCESS;
     }
   }

   if ((SerialNo == NULL) || (Length == NULL)) {
+    DEBUG ((DEBUG_ERROR, "#%a, %d: SerialNo is NULL\n", __func__, __LINE__));
     return EFI_INVALID_PARAMETER;
   }
+  DEBUG ((DEBUG_ERROR, "#%a, %d: before call LoadSNFromBlock SerialNo=%s\n", __func__, __LINE__, SerialNo));
   Status = LoadSNFromBlock (mFlashHandle, SERIAL_NUMBER_LBA, SerialNo);
   *Length = StrSize (SerialNo);
+  DEBUG ((DEBUG_ERROR, "#%a, %d: after call LoadSNFromBlock SerialNo=%s\n", __func__, __LINE__, SerialNo));
   return Status;
 }
liuyq commented 2 years ago

../edk2/MdePkg/Include/Uefi/UefiSpec.h

typedef
EFI_STATUS
(EFIAPI *EFI_OPEN_PROTOCOL)(
  IN  EFI_HANDLE                Handle,
  IN  EFI_GUID                  *Protocol,
  OUT VOID                      **Interface, OPTIONAL
  IN  EFI_HANDLE                AgentHandle,
  IN  EFI_HANDLE                ControllerHandle,
  IN  UINT32                    Attributes
  );

/**
  Closes a protocol on a handle that was opened using OpenProtocol().

  @param[in]  Handle            The handle for the protocol interface that was previously opened
                                with OpenProtocol(), and is now being closed.
  @param[in]  Protocol          The published unique identifier of the protocol.
  @param[in]  AgentHandle       The handle of the agent that is closing the protocol interface.
  @param[in]  ControllerHandle  If the agent that opened a protocol is a driver that follows the
                                UEFI Driver Model, then this parameter is the controller handle
                                that required the protocol interface.

  @retval EFI_SUCCESS           The protocol instance was closed.
  @retval EFI_INVALID_PARAMETER 1) Handle is NULL.
                                2) AgentHandle is NULL.
                                3) ControllerHandle is not NULL and ControllerHandle is not a valid EFI_HANDLE.
                                4) Protocol is NULL.
  @retval EFI_NOT_FOUND         1) Handle does not support the protocol specified by Protocol.
                                2) The protocol interface specified by Handle and Protocol is not
                                   currently open by AgentHandle and ControllerHandle.

**/
.....

///
/// EFI Boot Services Table.
///
typedef struct {
  ///
  /// The table header for the EFI Boot Services Table.
  ///
  EFI_TABLE_HEADER                Hdr;

  //
  // Task Priority Services
  //
  EFI_RAISE_TPL                   RaiseTPL;
  EFI_RESTORE_TPL                 RestoreTPL;

  //
  // Memory Services
  //
  EFI_ALLOCATE_PAGES              AllocatePages;
  EFI_FREE_PAGES                  FreePages;
  EFI_GET_MEMORY_MAP              GetMemoryMap;
  EFI_ALLOCATE_POOL               AllocatePool;
  EFI_FREE_POOL                   FreePool;

  //
  // Event & Timer Services
  //
  EFI_CREATE_EVENT                  CreateEvent;
  EFI_SET_TIMER                     SetTimer;
  EFI_WAIT_FOR_EVENT                WaitForEvent;
  EFI_SIGNAL_EVENT                  SignalEvent;
  EFI_CLOSE_EVENT                   CloseEvent;
  EFI_CHECK_EVENT                   CheckEvent;

  //
  // Protocol Handler Services
  //
  EFI_INSTALL_PROTOCOL_INTERFACE    InstallProtocolInterface;
  EFI_REINSTALL_PROTOCOL_INTERFACE  ReinstallProtocolInterface;
  EFI_UNINSTALL_PROTOCOL_INTERFACE  UninstallProtocolInterface;
  EFI_HANDLE_PROTOCOL               HandleProtocol;
  VOID                              *Reserved;
  EFI_REGISTER_PROTOCOL_NOTIFY      RegisterProtocolNotify;
  EFI_LOCATE_HANDLE                 LocateHandle;
  EFI_LOCATE_DEVICE_PATH            LocateDevicePath;
  EFI_INSTALL_CONFIGURATION_TABLE   InstallConfigurationTable;

  //
  // Image Services
  //
  EFI_IMAGE_LOAD                    LoadImage;
  EFI_IMAGE_START                   StartImage;
  EFI_EXIT                          Exit;
  EFI_IMAGE_UNLOAD                  UnloadImage;
  EFI_EXIT_BOOT_SERVICES            ExitBootServices;

  //
  // Miscellaneous Services
  //
  EFI_GET_NEXT_MONOTONIC_COUNT      GetNextMonotonicCount;
  EFI_STALL                         Stall;
  EFI_SET_WATCHDOG_TIMER            SetWatchdogTimer;

  //
  // DriverSupport Services
  //
  EFI_CONNECT_CONTROLLER            ConnectController;
  EFI_DISCONNECT_CONTROLLER         DisconnectController;

  //
  // Open and Close Protocol Services
  //
  EFI_OPEN_PROTOCOL                 OpenProtocol;
  EFI_CLOSE_PROTOCOL                CloseProtocol;
  EFI_OPEN_PROTOCOL_INFORMATION     OpenProtocolInformation;

  //
  // Library Services
  //
  EFI_PROTOCOLS_PER_HANDLE          ProtocolsPerHandle;
  EFI_LOCATE_HANDLE_BUFFER          LocateHandleBuffer;
  EFI_LOCATE_PROTOCOL               LocateProtocol;
  EFI_INSTALL_MULTIPLE_PROTOCOL_INTERFACES    InstallMultipleProtocolInterfaces;
  EFI_UNINSTALL_MULTIPLE_PROTOCOL_INTERFACES  UninstallMultipleProtocolInterfaces;

  //
  // 32-bit CRC Services
  //
  EFI_CALCULATE_CRC32               CalculateCrc32;

  //
  // Miscellaneous Services
  //
  EFI_COPY_MEM                      CopyMem;
  EFI_SET_MEM                       SetMem;
  EFI_CREATE_EVENT_EX               CreateEventEx;
} EFI_BOOT_SERVICES;
liuyq commented 2 years ago

Basic introduction on UFS:

https://casualhacking.io/blog/2018/10/6/exploring-universal-flash-storage-ufs-write-protection-on-the-hikey960 The boot flows is as follows:

    LUN0:0x0 xloader, closed source
    LUN3:0x200000 (fastboot partition) ARM-Trusted-Firmware's BL2, open source
    LUN3:0x1400000 (fip partition) ARM-Trusted-Firmware's FIP container, various
    mcuimage or lpm3 included as SCP_BL2 in the FIP container, closed source
    Optional OPTEE included as BL32 in the FIP container, open source
    UEFI included as BL33 in the FIP container, open source
    Your OS, open source

OpenPlatformPkg/Drivers/Block/DwUfsHcDxe/DwUfsHcDxe.inf MdeModulePkg/Bus/Ufs/UfsPassThruDxe/UfsPassThruDxe.inf MdeModulePkg/Bus/Scsi/ScsiBusDxe/ScsiBusDxe.inf MdeModulePkg/Bus/Scsi/ScsiDiskDxe/ScsiDiskDxe.inf

../edk2/MdeModulePkg/Include/Protocol/UfsHostController.h

typedef struct _EDKII_UFS_HOST_CONTROLLER_PROTOCOL  EDKII_UFS_HOST_CONTROLLER_PROTOCOL
///
///  UFS Host Controller Protocol structure.
///
struct _EDKII_UFS_HOST_CONTROLLER_PROTOCOL {
  EDKII_UFS_HC_GET_MMIO_BAR           GetUfsHcMmioBar;
  EDKII_UFS_HC_ALLOCATE_BUFFER        AllocateBuffer;
  EDKII_UFS_HC_FREE_BUFFER            FreeBuffer;
  EDKII_UFS_HC_MAP                    Map;
  EDKII_UFS_HC_UNMAP                  Unmap;
  EDKII_UFS_HC_FLUSH                  Flush;
  EDKII_UFS_HC_MMIO_READ_WRITE        Read;
  EDKII_UFS_HC_MMIO_READ_WRITE        Write;
  EDKII_UFS_HC_PHY_INIT               PhyInit;
  EDKII_UFS_HC_PHY_SET_POWER_MODE     PhySetPowerMode;
};

../edk2/MdeModulePkg/Bus/Pci/UfsPciHcDxe/UfsPciHcDxe.h

typedef struct _UFS_HOST_CONTROLLER_PRIVATE_DATA  UFS_HOST_CONTROLLER_PRIVATE_DATA;

//
// Nvme private data structure.
//
struct _UFS_HOST_CONTROLLER_PRIVATE_DATA {
  UINT32                             Signature;
  EFI_HANDLE                         Handle;

  EDKII_UFS_HOST_CONTROLLER_PROTOCOL UfsHc;
  EFI_PCI_IO_PROTOCOL                *PciIo;  
  UINT8                              BarIndex;
  UINT64                             PciAttributes;
};

../OpenPlatformPkg/Drivers/Block/DwUfsHcDxe/DwUfsHcDxe.h

typedef struct _UFS_HOST_CONTROLLER_PRIVATE_DATA  UFS_HOST_CONTROLLER_PRIVATE_DATA;

//
// Nvme private data structure.
//
struct _UFS_HOST_CONTROLLER_PRIVATE_DATA {
  UINT32                             Signature;
  EFI_HANDLE                         Handle;

  EDKII_UFS_HOST_CONTROLLER_PROTOCOL UfsHc;
  EFI_PCI_IO_PROTOCOL                *PciIo;
  UINT8                              BarIndex;
  UINT64                             PciAttributes;

  UINTN                              RegBase;
};

../OpenPlatformPkg/Drivers/Block/DwUfsHcDxe/DwUfsHcDxe.c

//
// Template for Ufs host controller private data.
//
UFS_HOST_CONTROLLER_PRIVATE_DATA gUfsHcTemplate = {
  UFS_HC_PRIVATE_DATA_SIGNATURE,  // Signature
  NULL,                           // Handle
  {                               // UfsHcProtocol
    UfsHcGetMmioBar,
    UfsHcAllocateBuffer,
    UfsHcFreeBuffer,
    UfsHcMap,
    UfsHcUnmap,
    UfsHcFlush,
    UfsHcMmioRead,
    UfsHcMmioWrite,
    UfsHcPhyInit,
    UfsHcPhySetPowerMode,
  },
  0                               // RegBase
};
liuyq commented 2 years ago

https://www.21ic.com/evm/evaluate/MCU/201706/724733_2.htm

Kirin960藏在DDR内存下面,这也是现在比较流行的一种封装方式,叫POP(Package on Package),就是右边这个,上面是LPDDR4 SDRAM,下面是Kirin 960。

开发板上的3GB LPDDR4 SDRAM是海力士的产品,4通道64位带宽,最高工作频率为1866MHz,通过总线直接与Kirin960的内存控制器接口相连。

上图中左边就是32GB的UFS外部存储器,兼容USF 2.0,UFS 2.0闪存读写速度理论上可以达到1400MB/s,不仅比eMMC有更巨大的优势,而且它甚至能够让电脑上使用的SSD也相形见绌。
Micro SD接口提供 SD 3.0接口,由Kirin960的SDC接口提供存取操作。
liuyq commented 1 year ago
writing 'super' 11/11...
OKAY [ 10.518s]
finished. total time: 315.201s
======= Flash userdata partition with file out/lkft-hikey960-android12-android12-5.10-gki//userdata.img ==============
target reported max download size of 134217728 bytes
erasing 'userdata'...
OKAY [  4.124s]
sending 'userdata' (184 KB)...
OKAY [  0.236s]
writing 'userdata'...
OKAY [  0.563s]
finished. total time: 4.922s
mke2fs 1.45.5 (07-Jan-2020)

Warning: RAID stripe-width 1 not an even multiple of stride 2.

/tmp/TemporaryFile-gpxzfP: Unimplemented ext2 library function while setting up superblock
/usr/lib/android-sdk/platform-tools/mke2fs failed with status 1
mke2fs failed: 1
error: Cannot generate image for cache

rebooting...

finished. total time: 2.206s
12:06:50 P15v:lkft-test$
#FastbootTransportUsbRequestReceive, 255, BufferSize:134213864
remove-symbol-file /home/liuyq/data/android/uefi-hikey960/Build/HiKey960/DEBUG_GCC5/AARCH64/EmbeddedPkg/Application/AndroidFastboot/AndroidFastbootApp/DEBUG/AndroidFastbootApp.dll 0xB9AF2000
  262656 / 134213864 bytes downloaded (0%)Image Return Status = Success
#CoreLocateDevicePath, 

Synchronous Exception at 0x00000000B9AF38DC

  X0 0x00000000BE2E8C98   X1 0x0000000000000000   X2 0x00000000B9AF38DC   X3 0x0000000000000000
  X4 0x0000000000000001   X5 0x0000000000000C02   X6 0x0000000000000001   X7 0x00000000BF18EBF0
  X8 0x00000000BF1D0A20   X9 0x00000000FFF06000  X10 0x0000000000000001  X11 0x0000000000000000
 X12 0x00000000703FE07A  X13 0x0000000000000000  X14 0x0000000000000000  X15 0x0000000000000000
 X16 0x00000000BFFFFA00  X17 0x0000000000000000  X18 0x0000000000000000  X19 0x0000000000000013
 X20 0x0000000000000000  X21 0x0000000000000000  X22 0x0000000000000000  X23 0x0000000000000000
 X24 0x0000000000000000  X25 0x0000000000000000  X26 0x0000000000000000  X27 0x0000000000000000
 X28 0x00000000BFFFF4B0   FP 0x00000000BFFFF2C0   LR 0x00000000BF1BB92C  

  V0 0xE9B5DBA5B5C0FBCF 71374491428A2F98   V1 0xAB1C5ED5923F82A4 59F111F13956C25B
  V2 0x550C7DC3243185BE 12835B01D807AA98   V3 0xC19BF1749BDC06A7 80DEB1FE72BE5D74
  V4 0x240CA1CC0FC19DC6 EFBE4786E49B69C1   V5 0x76F988DA5CB0A9DC 4A7484AA2DE92C6F
  V6 0xBF597FC7B00327C8 A831C66D983E5152   V7 0x1429296706CA6351 D5A79147C6E00BF3
  V8 0x0000000000000000 2E1B213827B70A85   V9 0x0000000000000000 766A0ABB650A7354
 V10 0x0000000000000000 A81A664BA2BFE8A1  V11 0x0000000000000000 D6990624D192E819
 V12 0x0000000000000000 1E376C0819A4C116  V13 0x0000000000000000 4ED8AA4A391C0CB3
 V14 0x0000000000000000 78A5636F748F82EE  V15 0x0000000000000000 A4506CEB90BEFFFA
 V16 0x3C83709547545153 BC990E9F897D4FA8  V17 0xBEBEF297C5EC0578 E1D99AE8C2B92607
 V18 0x13242833C5F05BAB 101C24C521387481  V19 0x0A50ABCAD0BDDA12 996865483E880969
 V20 0x6C4ABAA53A9BE1CB 4416D9F479B08221  V21 0x60952147C3A68574 55B8AE51435C1A1A
 V22 0x9FEB2A3B4AB8D3BF 88C1883495C7F76F  V23 0xD0C224BC8FB77E09 3DB8D233CF470963
 V24 0x0E72963E02D21C93 C95B757DA62B3A12  V25 0x2A77DBA1E4EE5D5C E08479A1B557DFA8
 V26 0xB593F86668CA8129 927A0019CDEC1A76  V27 0xBFFEF500BD4A3DDF 9FF51E18577FFF6B
 V28 0x9DFA7DE325AF967F 6F3B5DCAFFF3FFCF  V29 0xFBF3F9FD0E649C7E BCF65577E9D77CDE
 V30 0x46FFEBFFA5B7CC34 C5FDBD07F3377D77  V31 0xBCA7F7EC79DBE957 49FFEAB79F37D7FF

  SP 0x00000000BFFFF2C0  ELR 0x00000000B9AF38DC  SPSR 0x20000309  FPSR 0x00000000
 ESR 0x02000000          FAR 0xFC357DF63396F47F

 ESR : EC 0x00  IL 0x1  ISS 0x00000000

Stack dump:
  00000BFFFF1C0: 996865483E880969 0A50ABCAD0BDDA12 4416D9F479B08221 6C4ABAA53A9BE1CB
  00000BFFFF1E0: 55B8AE51435C1A1A 60952147C3A68574 88C1883495C7F76F 9FEB2A3B4AB8D3BF
  00000BFFFF200: 3DB8D233CF470963 D0C224BC8FB77E09 C95B757DA62B3A12 0E72963E02D21C93
  00000BFFFF220: E08479A1B557DFA8 2A77DBA1E4EE5D5C 927A0019CDEC1A76 B593F86668CA8129
  00000BFFFF240: 9FF51E18577FFF6B BFFEF500BD4A3DDF 6F3B5DCAFFF3FFCF 9DFA7DE325AF967F
  00000BFFFF260: BCF65577E9D77CDE FBF3F9FD0E649C7E C5FDBD07F3377D77 46FFEBFFA5B7CC34
  00000BFFFF280: 49FFEAB79F37D7FF BCA7F7EC79DBE957 00000000B9AF38DC 0000000020000309
  00000BFFFF2A0: 0000000000000000 0000000002000000 FC357DF63396F47F 00000000BF1BB8D4
> 00000BFFFF2C0: 00000000BFFFF2F0 00000000BF1BB0AC 00000000BFFFF2F0 0000000000000008
  00000BFFFF2E0: 00000000BE2E8C98 00000000BF1D9480 00000000BFFFF320 00000000BEFCB750
  00000BFFFF300: 00000000BFFFF320 0000000000000004 000000000000001E 000000000000001F
  00000BFFFF320: 00000000BFFFF360 00000000BF034794 00000000BFFFF3B0 000000000000001E
  00000BFFFF340: 00000000BFFFF360 000000001BD9D6C2 0000000000000004 000000001BD9D77F
  00000BFFFF360: 00000000BFFFF390 00000000BF0D4FE4 00000000BFFFF3B0 0000000000000001
  00000BFFFF380: 00000000BEFCB608 0000001E243185BE 00000000BFFFF6E0 00000000BF0D512C
  00000BFFFF3A0: 00000000BFFFF3B0 0000000000000001 0000000000000039 00000000BFFFF7E7
ASSERT [ArmCpuDxe] /home/liuyq/data/android/uefi-hikey960/edk2/ArmPkg/Library/DefaultExceptionHandlerLib/AArch64/DefaultExceptionHandler.c(265): ((BOOLEAN)(0==1))