From 74e8db0ed15ec0dc7ed5408dfe84f2a9a675d231 Mon Sep 17 00:00:00 2001 From: robert-hh Date: Tue, 30 Nov 2021 20:23:03 +0100 Subject: [PATCH] mimxrt: Refactor the reading of the machine id. The ID is read in a single function and used for: - machine.unique_id() - Ethernet MAC addresses. - ... That facilitates use of other MCU using a different access method for the ID (e.g. i.MX RT1176). --- ports/mimxrt/modmachine.c | 5 +---- ports/mimxrt/mphalport.c | 18 +++++++++++++++--- ports/mimxrt/mphalport.h | 1 + 3 files changed, 17 insertions(+), 7 deletions(-) diff --git a/ports/mimxrt/modmachine.c b/ports/mimxrt/modmachine.c index e7f0961344..63cec05507 100644 --- a/ports/mimxrt/modmachine.c +++ b/ports/mimxrt/modmachine.c @@ -37,7 +37,6 @@ #include "pin.h" #include "modmachine.h" #include "fsl_clock.h" -#include "fsl_ocotp.h" #include "fsl_wdog.h" #include CPU_HEADER_H @@ -52,9 +51,7 @@ typedef enum { STATIC mp_obj_t machine_unique_id(void) { unsigned char id[8]; - OCOTP_Init(OCOTP, CLOCK_GetFreq(kCLOCK_IpgClk)); - *(uint32_t *)&id[0] = OCOTP->CFG0; - *(uint32_t *)&id[4] = OCOTP->CFG1; + mp_hal_get_unique_id(id); return mp_obj_new_bytes(id, sizeof(id)); } MP_DEFINE_CONST_FUN_OBJ_0(machine_unique_id_obj, machine_unique_id); diff --git a/ports/mimxrt/mphalport.c b/ports/mimxrt/mphalport.c index 66498d7b27..17a6898c40 100644 --- a/ports/mimxrt/mphalport.c +++ b/ports/mimxrt/mphalport.c @@ -123,13 +123,25 @@ uint64_t mp_hal_time_ns(void) { /*******************************************************************************/ // MAC address +void mp_hal_get_unique_id(uint8_t id[]) { + OCOTP_Init(OCOTP, CLOCK_GetFreq(kCLOCK_IpgClk)); + *(uint32_t *)&id[0] = OCOTP->CFG0; + *(uint32_t *)&id[4] = OCOTP->CFG1; +} + // Generate a random locally administered MAC address (LAA) void mp_hal_generate_laa_mac(int idx, uint8_t buf[6]) { // Take the MAC addr from the OTP's Configuration and Manufacturing Info - OCOTP_Init(OCOTP, CLOCK_GetFreq(kCLOCK_IpgClk)); + unsigned char id[8]; + mp_hal_get_unique_id(id); + + uint32_t pt1 = *(uint32_t *)&id[0]; + uint32_t pt2 = *(uint32_t *)&id[4]; + buf[0] = 0x02; // Locally Administered MAC - *(uint32_t *)&buf[1] = OCOTP->CFG0 ^ (OCOTP->CFG0 >> 8); - *(uint16_t *)&buf[4] = (uint16_t)(OCOTP->CFG1 ^ (OCOTP->CFG1 >> 16)); + *(uint32_t *)&buf[1] = pt1 ^ (pt1 >> 8); + *(uint16_t *)&buf[4] = (uint16_t)(pt2 ^ pt2 >> 16); + buf[5] ^= (uint8_t)idx; } // A board can override this if needed diff --git a/ports/mimxrt/mphalport.h b/ports/mimxrt/mphalport.h index 5210ff44a3..124b905604 100644 --- a/ports/mimxrt/mphalport.h +++ b/ports/mimxrt/mphalport.h @@ -103,5 +103,6 @@ enum { void mp_hal_generate_laa_mac(int idx, uint8_t buf[6]); void mp_hal_get_mac(int idx, uint8_t buf[6]); void mp_hal_get_mac_ascii(int idx, size_t chr_off, size_t chr_len, char *dest); +void mp_hal_get_unique_id(uint8_t id[]); #endif // MICROPY_INCLUDED_MIMXRT_MPHALPORT_H