1# SPDX-FileCopyrightText: 2014-2022 Fredrik Ahlberg, Angus Gratton,
2# Espressif Systems (Shanghai) CO LTD, other contributors as noted.
3#
4# SPDX-License-Identifier: GPL-2.0-or-later
5
6import struct
7import time
8
9from .esp32c3 import ESP32C3ROM
10from ..loader import ESPLoader
11from ..util import FatalError
12
13
14class ESP32C2ROM(ESP32C3ROM):
15    CHIP_NAME = "ESP32-C2"
16    IMAGE_CHIP_ID = 12
17
18    IROM_MAP_START = 0x42000000
19    IROM_MAP_END = 0x42400000
20    DROM_MAP_START = 0x3C000000
21    DROM_MAP_END = 0x3C400000
22
23    # Magic value for ESP32C2 ECO0 and ECO1 respectively
24    CHIP_DETECT_MAGIC_VALUE = [0x6F51306F, 0x7C41A06F]
25
26    EFUSE_BASE = 0x60008800
27    EFUSE_BLOCK2_ADDR = EFUSE_BASE + 0x040
28    MAC_EFUSE_REG = EFUSE_BASE + 0x040
29
30    EFUSE_SECURE_BOOT_EN_REG = EFUSE_BASE + 0x30
31    EFUSE_SECURE_BOOT_EN_MASK = 1 << 21
32
33    EFUSE_SPI_BOOT_CRYPT_CNT_REG = EFUSE_BASE + 0x30
34    EFUSE_SPI_BOOT_CRYPT_CNT_MASK = 0x7 << 18
35
36    EFUSE_DIS_DOWNLOAD_MANUAL_ENCRYPT_REG = EFUSE_BASE + 0x30
37    EFUSE_DIS_DOWNLOAD_MANUAL_ENCRYPT = 1 << 6
38
39    EFUSE_XTS_KEY_LENGTH_256_REG = EFUSE_BASE + 0x30
40    EFUSE_XTS_KEY_LENGTH_256 = 1 << 10
41
42    EFUSE_BLOCK_KEY0_REG = EFUSE_BASE + 0x60
43
44    EFUSE_RD_DIS_REG = EFUSE_BASE + 0x30
45    EFUSE_RD_DIS = 3
46
47    FLASH_FREQUENCY = {
48        "60m": 0xF,
49        "30m": 0x0,
50        "20m": 0x1,
51        "15m": 0x2,
52    }
53
54    MEMORY_MAP = [
55        [0x00000000, 0x00010000, "PADDING"],
56        [0x3C000000, 0x3C400000, "DROM"],
57        [0x3FCA0000, 0x3FCE0000, "DRAM"],
58        [0x3FC88000, 0x3FD00000, "BYTE_ACCESSIBLE"],
59        [0x3FF00000, 0x3FF50000, "DROM_MASK"],
60        [0x40000000, 0x40090000, "IROM_MASK"],
61        [0x42000000, 0x42400000, "IROM"],
62        [0x4037C000, 0x403C0000, "IRAM"],
63    ]
64
65    UF2_FAMILY_ID = 0x2B88D29C
66
67    def get_pkg_version(self):
68        num_word = 1
69        return (self.read_reg(self.EFUSE_BLOCK2_ADDR + (4 * num_word)) >> 22) & 0x07
70
71    def get_chip_description(self):
72        chip_name = {
73            0: "ESP32-C2",
74            1: "ESP32-C2",
75        }.get(self.get_pkg_version(), "unknown ESP32-C2")
76        major_rev = self.get_major_chip_version()
77        minor_rev = self.get_minor_chip_version()
78        return f"{chip_name} (revision v{major_rev}.{minor_rev})"
79
80    def get_minor_chip_version(self):
81        num_word = 1
82        return (self.read_reg(self.EFUSE_BLOCK2_ADDR + (4 * num_word)) >> 16) & 0xF
83
84    def get_major_chip_version(self):
85        num_word = 1
86        return (self.read_reg(self.EFUSE_BLOCK2_ADDR + (4 * num_word)) >> 20) & 0x3
87
88    def get_flash_cap(self):
89        # ESP32-C2 doesn't have eFuse field FLASH_CAP.
90        # Can't get info about the flash chip.
91        return 0
92
93    def get_flash_vendor(self):
94        # ESP32-C2 doesn't have eFuse field FLASH_VENDOR.
95        # Can't get info about the flash chip.
96        return ""
97
98    def get_crystal_freq(self):
99        # The crystal detection algorithm of ESP32/ESP8266 works for ESP32-C2 as well.
100        return ESPLoader.get_crystal_freq(self)
101
102    def change_baud(self, baud):
103        rom_with_26M_XTAL = not self.IS_STUB and self.get_crystal_freq() == 26
104        if rom_with_26M_XTAL:
105            # The code is copied over from ESPLoader.change_baud().
106            # Probably this is just a temporary solution until the next chip revision.
107
108            # The ROM code thinks it uses a 40 MHz XTAL. Recompute the baud rate
109            # in order to trick the ROM code to set the correct baud rate for
110            # a 26 MHz XTAL.
111            false_rom_baud = baud * 40 // 26
112
113            print(f"Changing baud rate to {baud}")
114            self.command(
115                self.ESP_CHANGE_BAUDRATE, struct.pack("<II", false_rom_baud, 0)
116            )
117            print("Changed.")
118            self._set_port_baudrate(baud)
119            time.sleep(0.05)  # get rid of garbage sent during baud rate change
120            self.flush_input()
121        else:
122            ESPLoader.change_baud(self, baud)
123
124    def _post_connect(self):
125        # ESP32C2 ECO0 is no longer supported by the flasher stub
126        if not self.secure_download_mode and self.get_chip_revision() == 0:
127            self.stub_is_disabled = True
128            self.IS_STUB = False
129
130    """ Try to read (encryption key) and check if it is valid """
131
132    def is_flash_encryption_key_valid(self):
133        key_len_256 = (
134            self.read_reg(self.EFUSE_XTS_KEY_LENGTH_256_REG)
135            & self.EFUSE_XTS_KEY_LENGTH_256
136        )
137
138        word0 = self.read_reg(self.EFUSE_RD_DIS_REG) & self.EFUSE_RD_DIS
139        rd_disable = word0 == 3 if key_len_256 else word0 == 1
140
141        # reading of BLOCK3 is NOT ALLOWED so we assume valid key is programmed
142        if rd_disable:
143            return True
144        else:
145            # reading of BLOCK3 is ALLOWED so we will read and verify for non-zero.
146            # When chip has not generated AES/encryption key in BLOCK3,
147            # the contents will be readable and 0.
148            # If the flash encryption is enabled it is expected to have a valid
149            # non-zero key. We break out on first occurrence of non-zero value
150            key_word = [0] * 7 if key_len_256 else [0] * 3
151            for i in range(len(key_word)):
152                key_word[i] = self.read_reg(self.EFUSE_BLOCK_KEY0_REG + i * 4)
153                # key is non-zero so break & return
154                if key_word[i] != 0:
155                    return True
156            return False
157
158    def check_spi_connection(self, spi_connection):
159        if not set(spi_connection).issubset(set(range(0, 21))):
160            raise FatalError("SPI Pin numbers must be in the range 0-20.")
161
162
163class ESP32C2StubLoader(ESP32C2ROM):
164    """Access class for ESP32C2 stub loader, runs on top of ROM.
165
166    (Basically the same as ESP32StubLoader, but different base class.
167    Can possibly be made into a mixin.)
168    """
169
170    FLASH_WRITE_SIZE = 0x4000  # matches MAX_WRITE_BLOCK in stub_loader.c
171    STATUS_BYTES_LENGTH = 2  # same as ESP8266, different to ESP32 ROM
172    IS_STUB = True
173
174    def __init__(self, rom_loader):
175        self.secure_download_mode = rom_loader.secure_download_mode
176        self._port = rom_loader._port
177        self._trace_enabled = rom_loader._trace_enabled
178        self.cache = rom_loader.cache
179        self.flush_input()  # resets _slip_reader
180
181
182ESP32C2ROM.STUB_CLASS = ESP32C2StubLoader
183