1# This file describes eFuses for ESP32-H2 chip
2#
3# SPDX-FileCopyrightText: 2021-2022 Espressif Systems (Shanghai) CO LTD
4#
5# SPDX-License-Identifier: GPL-2.0-or-later
6
7import binascii
8import struct
9import time
10
11from bitstring import BitArray
12
13import esptool
14
15import reedsolo
16
17from .mem_definition import EfuseDefineBlocks, EfuseDefineFields, EfuseDefineRegisters
18from .. import base_fields
19from .. import util
20
21
22class EfuseBlock(base_fields.EfuseBlockBase):
23    def len_of_burn_unit(self):
24        # The writing register window is 8 registers for any blocks.
25        # len in bytes
26        return 8 * 4
27
28    def __init__(self, parent, param, skip_read=False):
29        parent.read_coding_scheme()
30        super(EfuseBlock, self).__init__(parent, param, skip_read=skip_read)
31
32    def apply_coding_scheme(self):
33        data = self.get_raw(from_read=False)[::-1]
34        if len(data) < self.len_of_burn_unit():
35            add_empty_bytes = self.len_of_burn_unit() - len(data)
36            data = data + (b"\x00" * add_empty_bytes)
37        if self.get_coding_scheme() == self.parent.REGS.CODING_SCHEME_RS:
38            # takes 32 bytes
39            # apply RS encoding
40            rs = reedsolo.RSCodec(12)
41            # 32 byte of data + 12 bytes RS
42            encoded_data = rs.encode([x for x in data])
43            words = struct.unpack("<" + "I" * 11, encoded_data)
44            # returns 11 words (8 words of data + 3 words of RS coding)
45        else:
46            # takes 32 bytes
47            words = struct.unpack("<" + ("I" * (len(data) // 4)), data)
48            # returns 8 words
49        return words
50
51
52class EspEfuses(base_fields.EspEfusesBase):
53    """
54    Wrapper object to manage the efuse fields in a connected ESP bootloader
55    """
56
57    Blocks = EfuseDefineBlocks()
58    Fields = EfuseDefineFields()
59    REGS = EfuseDefineRegisters
60    BURN_BLOCK_DATA_NAMES = Blocks.get_burn_block_data_names()
61    BLOCKS_FOR_KEYS = Blocks.get_blocks_for_keys()
62
63    debug = False
64    do_not_confirm = False
65
66    def __init__(self, esp, skip_connect=False, debug=False, do_not_confirm=False):
67        self._esp = esp
68        self.debug = debug
69        self.do_not_confirm = do_not_confirm
70        if esp.CHIP_NAME != "ESP32-H2(beta1)":
71            raise esptool.FatalError(
72                "Expected the 'esp' param for ESP32-H2(beta1) chip but got for '%s'."
73                % (esp.CHIP_NAME)
74            )
75        if not skip_connect:
76            flags = self._esp.get_security_info()["flags"]
77            GET_SECURITY_INFO_FLAG_SECURE_DOWNLOAD_ENABLE = 1 << 2
78            if flags & GET_SECURITY_INFO_FLAG_SECURE_DOWNLOAD_ENABLE:
79                raise esptool.FatalError(
80                    "Secure Download Mode is enabled. The tool can not read eFuses."
81                )
82        self.blocks = [
83            EfuseBlock(self, self.Blocks.get(block), skip_read=skip_connect)
84            for block in self.Blocks.BLOCKS
85        ]
86        if not skip_connect:
87            self.get_coding_scheme_warnings()
88        self.efuses = [
89            EfuseField.from_tuple(
90                self, self.Fields.get(efuse), self.Fields.get(efuse).class_type
91            )
92            for efuse in self.Fields.EFUSES
93        ]
94        self.efuses += [
95            EfuseField.from_tuple(
96                self, self.Fields.get(efuse), self.Fields.get(efuse).class_type
97            )
98            for efuse in self.Fields.KEYBLOCKS
99        ]
100        if skip_connect:
101            self.efuses += [
102                EfuseField.from_tuple(
103                    self, self.Fields.get(efuse), self.Fields.get(efuse).class_type
104                )
105                for efuse in self.Fields.BLOCK2_CALIBRATION_EFUSES
106            ]
107        else:
108            if self["BLOCK2_VERSION"].get() == 1:
109                self.efuses += [
110                    EfuseField.from_tuple(
111                        self, self.Fields.get(efuse), self.Fields.get(efuse).class_type
112                    )
113                    for efuse in self.Fields.BLOCK2_CALIBRATION_EFUSES
114                ]
115
116    def __getitem__(self, efuse_name):
117        """Return the efuse field with the given name"""
118        for e in self.efuses:
119            if efuse_name == e.name:
120                return e
121        new_fields = False
122        for efuse in self.Fields.BLOCK2_CALIBRATION_EFUSES:
123            e = self.Fields.get(efuse)
124            if e.name == efuse_name:
125                self.efuses += [
126                    EfuseField.from_tuple(
127                        self, self.Fields.get(efuse), self.Fields.get(efuse).class_type
128                    )
129                    for efuse in self.Fields.BLOCK2_CALIBRATION_EFUSES
130                ]
131                new_fields = True
132        if new_fields:
133            for e in self.efuses:
134                if efuse_name == e.name:
135                    return e
136        raise KeyError
137
138    def read_coding_scheme(self):
139        self.coding_scheme = self.REGS.CODING_SCHEME_RS
140
141    def print_status_regs(self):
142        print("")
143        self.blocks[0].print_block(self.blocks[0].err_bitarray, "err__regs", debug=True)
144        print(
145            "{:27} 0x{:08x}".format(
146                "EFUSE_RD_RS_ERR0_REG", self.read_reg(self.REGS.EFUSE_RD_RS_ERR0_REG)
147            )
148        )
149        print(
150            "{:27} 0x{:08x}".format(
151                "EFUSE_RD_RS_ERR1_REG", self.read_reg(self.REGS.EFUSE_RD_RS_ERR1_REG)
152            )
153        )
154
155    def get_block_errors(self, block_num):
156        """Returns (error count, failure boolean flag)"""
157        return self.blocks[block_num].num_errors, self.blocks[block_num].fail
158
159    def efuse_controller_setup(self):
160        self.set_efuse_timing()
161        self.clear_pgm_registers()
162        self.wait_efuse_idle()
163
164    def write_efuses(self, block):
165        self.efuse_program(block)
166        return self.get_coding_scheme_warnings(silent=True)
167
168    def clear_pgm_registers(self):
169        self.wait_efuse_idle()
170        for r in range(
171            self.REGS.EFUSE_PGM_DATA0_REG, self.REGS.EFUSE_PGM_DATA0_REG + 32, 4
172        ):
173            self.write_reg(r, 0)
174
175    def wait_efuse_idle(self):
176        deadline = time.time() + self.REGS.EFUSE_BURN_TIMEOUT
177        while time.time() < deadline:
178            # if self.read_reg(self.REGS.EFUSE_CMD_REG) == 0:
179            if self.read_reg(self.REGS.EFUSE_STATUS_REG) & 0x7 == 1:
180                return
181        raise esptool.FatalError(
182            "Timed out waiting for Efuse controller command to complete"
183        )
184
185    def efuse_program(self, block):
186        self.wait_efuse_idle()
187        self.write_reg(self.REGS.EFUSE_CONF_REG, self.REGS.EFUSE_WRITE_OP_CODE)
188        self.write_reg(self.REGS.EFUSE_CMD_REG, self.REGS.EFUSE_PGM_CMD | (block << 2))
189        self.wait_efuse_idle()
190        self.clear_pgm_registers()
191        self.efuse_read()
192
193    def efuse_read(self):
194        self.wait_efuse_idle()
195        self.write_reg(self.REGS.EFUSE_CONF_REG, self.REGS.EFUSE_READ_OP_CODE)
196        # need to add a delay after triggering EFUSE_READ_CMD, as ROM loader checks some
197        # efuse registers after each command is completed
198        # if ENABLE_SECURITY_DOWNLOAD or DIS_DOWNLOAD_MODE is enabled by the current cmd, then we need to try to reconnect to the chip.
199        try:
200            self.write_reg(
201                self.REGS.EFUSE_CMD_REG, self.REGS.EFUSE_READ_CMD, delay_after_us=1000
202            )
203            self.wait_efuse_idle()
204        except esptool.FatalError:
205            secure_download_mode_before = self._esp.secure_download_mode
206
207            try:
208                self._esp = self.reconnect_chip(self._esp)
209            except esptool.FatalError:
210                print("Can not re-connect to the chip")
211                if not self["DIS_DOWNLOAD_MODE"].get() and self[
212                    "DIS_DOWNLOAD_MODE"
213                ].get(from_read=False):
214                    print(
215                        "This is the correct behavior as we are actually burning "
216                        "DIS_DOWNLOAD_MODE which disables the connection to the chip"
217                    )
218                    print("DIS_DOWNLOAD_MODE is enabled")
219                    print("Successful")
220                    exit(0)  # finish without errors
221                raise
222
223            print("Established a connection with the chip")
224            if self._esp.secure_download_mode and not secure_download_mode_before:
225                print("Secure download mode is enabled")
226                if not self["ENABLE_SECURITY_DOWNLOAD"].get() and self[
227                    "ENABLE_SECURITY_DOWNLOAD"
228                ].get(from_read=False):
229                    print(
230                        "espefuse tool can not continue to work in Secure download mode"
231                    )
232                    print("ENABLE_SECURITY_DOWNLOAD is enabled")
233                    print("Successful")
234                    exit(0)  # finish without errors
235            raise
236
237    def set_efuse_timing(self):
238        """Set timing registers for burning efuses"""
239        # Configure clock
240        apb_freq = self.get_crystal_freq()
241        if apb_freq != 32:
242            raise esptool.FatalError(
243                "The eFuse supports only xtal=32M (xtal was %d)" % apb_freq
244            )
245
246        self.update_reg(
247            self.REGS.EFUSE_WR_TIM_CONF2_REG, self.REGS.EFUSE_PWR_OFF_NUM_M, 0x190
248        )
249
250    def get_coding_scheme_warnings(self, silent=False):
251        """Check if the coding scheme has detected any errors."""
252        old_addr_reg = 0
253        reg_value = 0
254        ret_fail = False
255        for block in self.blocks:
256            if block.id == 0:
257                words = [
258                    self.read_reg(self.REGS.EFUSE_RD_REPEAT_ERR0_REG + offs * 4)
259                    for offs in range(5)
260                ]
261                data = BitArray()
262                for word in reversed(words):
263                    data.append("uint:32=%d" % word)
264                # pos=32 because EFUSE_WR_DIS goes first it is 32bit long
265                # and not under error control
266                block.err_bitarray.overwrite(data, pos=32)
267                block.num_errors = block.err_bitarray.count(True)
268                block.fail = block.num_errors != 0
269            else:
270                addr_reg, err_num_mask, err_num_offs, fail_bit = self.REGS.BLOCK_ERRORS[
271                    block.id
272                ]
273                if err_num_mask is None or err_num_offs is None or fail_bit is None:
274                    continue
275                if addr_reg != old_addr_reg:
276                    old_addr_reg = addr_reg
277                    reg_value = self.read_reg(addr_reg)
278                block.fail = reg_value & (1 << fail_bit) != 0
279                block.num_errors = (reg_value >> err_num_offs) & err_num_mask
280            ret_fail |= block.fail
281            if not silent and (block.fail or block.num_errors):
282                print(
283                    "Error(s) in BLOCK%d [ERRORS:%d FAIL:%d]"
284                    % (block.id, block.num_errors, block.fail)
285                )
286        if (self.debug or ret_fail) and not silent:
287            self.print_status_regs()
288        return ret_fail
289
290    def summary(self):
291        # TODO add support set_flash_voltage - "Flash voltage (VDD_SPI)"
292        return ""
293
294
295class EfuseField(base_fields.EfuseFieldBase):
296    @staticmethod
297    def from_tuple(parent, efuse_tuple, type_class):
298        return {
299            "mac": EfuseMacField,
300            "keypurpose": EfuseKeyPurposeField,
301            "t_sensor": EfuseTempSensor,
302            "adc_tp": EfuseAdcPointCalibration,
303        }.get(type_class, EfuseField)(parent, efuse_tuple)
304
305    def get_info(self):
306        output = "%s (BLOCK%d)" % (self.name, self.block)
307        errs, fail = self.parent.get_block_errors(self.block)
308        if errs != 0 or fail:
309            output += (
310                "[FAIL:%d]" % (fail)
311                if self.block == 0
312                else "[ERRS:%d FAIL:%d]" % (errs, fail)
313            )
314        if self.efuse_class == "keyblock":
315            name = self.parent.blocks[self.block].key_purpose_name
316            if name is not None:
317                output += "\n  Purpose: %s\n " % (self.parent[name].get())
318        return output
319
320
321class EfuseTempSensor(EfuseField):
322    def get(self, from_read=True):
323        value = self.get_bitstring(from_read)
324        sig = -1 if value[0] else 1
325        return sig * value[1:].uint * 0.1
326
327
328class EfuseAdcPointCalibration(EfuseField):
329    def get(self, from_read=True):
330        STEP_SIZE = 4
331        value = self.get_bitstring(from_read)
332        sig = -1 if value[0] else 1
333        return sig * value[1:].uint * STEP_SIZE
334
335
336class EfuseMacField(EfuseField):
337    def check_format(self, new_value_str):
338        if new_value_str is None:
339            raise esptool.FatalError(
340                "Required MAC Address in AA:CD:EF:01:02:03 format!"
341            )
342        if new_value_str.count(":") != 5:
343            raise esptool.FatalError(
344                "MAC Address needs to be a 6-byte hexadecimal format "
345                "separated by colons (:)!"
346            )
347        hexad = new_value_str.replace(":", "")
348        if len(hexad) != 12:
349            raise esptool.FatalError(
350                "MAC Address needs to be a 6-byte hexadecimal number "
351                "(12 hexadecimal characters)!"
352            )
353        # order of bytearray = b'\xaa\xcd\xef\x01\x02\x03',
354        bindata = binascii.unhexlify(hexad)
355        # unicast address check according to
356        # https://tools.ietf.org/html/rfc7042#section-2.1
357        if esptool.util.byte(bindata, 0) & 0x01:
358            raise esptool.FatalError("Custom MAC must be a unicast MAC!")
359        return bindata
360
361    def check(self):
362        errs, fail = self.parent.get_block_errors(self.block)
363        if errs != 0 or fail:
364            output = "Block%d has ERRORS:%d FAIL:%d" % (self.block, errs, fail)
365        else:
366            output = "OK"
367        return "(" + output + ")"
368
369    def get(self, from_read=True):
370        if self.name == "CUSTOM_MAC":
371            mac = self.get_raw(from_read)[::-1] + self.parent["MAC_EXT"].get_raw(
372                from_read
373            )
374        elif self.name == "MAC":
375            mac = self.get_raw(from_read) + self.parent["MAC_EXT"].get_raw(from_read)
376        else:
377            mac = self.get_raw(from_read)
378        return "%s %s" % (util.hexify(mac, ":"), self.check())
379
380    def save(self, new_value):
381        def print_field(e, new_value):
382            print(
383                "    - '{}' ({}) {} -> {}".format(
384                    e.name, e.description, e.get_bitstring(), new_value
385                )
386            )
387
388        if self.name == "CUSTOM_MAC":
389            bitarray_mac = self.convert_to_bitstring(new_value)
390            print_field(self, bitarray_mac)
391            super(EfuseMacField, self).save(new_value)
392        else:
393            # Writing the BLOCK1 (MAC_SPI_8M_0) default MAC is not possible,
394            # as it's written in the factory.
395            raise esptool.FatalError("Writing Factory MAC address is not supported")
396
397
398# fmt: off
399class EfuseKeyPurposeField(EfuseField):
400    KEY_PURPOSES = [
401        ("USER",                         0,  None,       None,      "no_need_rd_protect"),   # User purposes (software-only use)
402        ("RESERVED",                     1,  None,       None,      "no_need_rd_protect"),   # Reserved
403        ("XTS_AES_256_KEY_1",            2,  None,       "Reverse", "need_rd_protect"),      # XTS_AES_256_KEY_1 (flash/PSRAM encryption)
404        ("XTS_AES_256_KEY_2",            3,  None,       "Reverse", "need_rd_protect"),      # XTS_AES_256_KEY_2 (flash/PSRAM encryption)
405        ("XTS_AES_128_KEY",              4,  None,       "Reverse", "need_rd_protect"),      # XTS_AES_128_KEY (flash/PSRAM encryption)
406        ("HMAC_DOWN_ALL",                5,  None,       None,      "need_rd_protect"),      # HMAC Downstream mode
407        ("HMAC_DOWN_JTAG",               6,  None,       None,      "need_rd_protect"),      # JTAG soft enable key (uses HMAC Downstream mode)
408        ("HMAC_DOWN_DIGITAL_SIGNATURE",  7,  None,       None,      "need_rd_protect"),      # Digital Signature peripheral key (uses HMAC Downstream mode)
409        ("HMAC_UP",                      8,  None,       None,      "need_rd_protect"),      # HMAC Upstream mode
410        ("SECURE_BOOT_DIGEST0",          9,  "DIGEST",   None,      "no_need_rd_protect"),   # SECURE_BOOT_DIGEST0 (Secure Boot key digest)
411        ("SECURE_BOOT_DIGEST1",          10, "DIGEST",   None,      "no_need_rd_protect"),   # SECURE_BOOT_DIGEST1 (Secure Boot key digest)
412        ("SECURE_BOOT_DIGEST2",          11, "DIGEST",   None,      "no_need_rd_protect"),   # SECURE_BOOT_DIGEST2 (Secure Boot key digest)
413    ]
414# fmt: on
415
416    KEY_PURPOSES_NAME = [name[0] for name in KEY_PURPOSES]
417    DIGEST_KEY_PURPOSES = [name[0] for name in KEY_PURPOSES if name[2] == "DIGEST"]
418
419    def check_format(self, new_value_str):
420        # str convert to int: "XTS_AES_128_KEY" - > str(4)
421        # if int: 4 -> str(4)
422        raw_val = new_value_str
423        for purpose_name in self.KEY_PURPOSES:
424            if purpose_name[0] == new_value_str:
425                raw_val = str(purpose_name[1])
426                break
427        if raw_val.isdigit():
428            if int(raw_val) not in [p[1] for p in self.KEY_PURPOSES if p[1] > 0]:
429                raise esptool.FatalError("'%s' can not be set (value out of range)" % raw_val)
430        else:
431            raise esptool.FatalError("'%s' unknown name" % raw_val)
432        return raw_val
433
434    def need_reverse(self, new_key_purpose):
435        for key in self.KEY_PURPOSES:
436            if key[0] == new_key_purpose:
437                return key[3] == "Reverse"
438
439    def need_rd_protect(self, new_key_purpose):
440        for key in self.KEY_PURPOSES:
441            if key[0] == new_key_purpose:
442                return key[4] == "need_rd_protect"
443
444    def get(self, from_read=True):
445        for p in self.KEY_PURPOSES:
446            if p[1] == self.get_raw(from_read):
447                return p[0]
448        return "FORBIDDEN_STATE"
449
450    def save(self, new_value):
451        raw_val = int(self.check_format(str(new_value)))
452        return super(EfuseKeyPurposeField, self).save(raw_val)
453