├── nandbug_platform ├── ice_ftdi │ ├── __init__.py │ └── ice_ftdi.py ├── __init__.py └── nand_bug_platform.py ├── requirements.txt ├── bitstreams ├── modules │ ├── __init__.py │ ├── blinker.py │ ├── ftdi_fifo.py │ └── nand_fsm.py ├── __init__.py ├── passthrough.py ├── erase.py ├── dump.py └── program.py ├── NandBugPassthrough.py ├── .gitignore ├── LICENSE ├── NandBugDumper.py ├── README.md └── NandBugPatcher.py /nandbug_platform/ice_ftdi/__init__.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python3 2 | 3 | from .ice_ftdi import * -------------------------------------------------------------------------------- /requirements.txt: -------------------------------------------------------------------------------- 1 | nmigen==0.2 2 | bchlib==0.14.0 3 | nmigen_boards==0.0 4 | pylibftdi==0.17.0 5 | halo==0.0.29 6 | -------------------------------------------------------------------------------- /nandbug_platform/__init__.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python3 2 | 3 | from .ice_ftdi import * 4 | from .nand_bug_platform import NandBugPlatform 5 | -------------------------------------------------------------------------------- /bitstreams/modules/__init__.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python3 2 | 3 | from .blinker import Blinker 4 | from .ftdi_fifo import FtdiFifo 5 | from .nand_fsm import NandFSM 6 | -------------------------------------------------------------------------------- /bitstreams/__init__.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python3 2 | 3 | from .dump import Dump 4 | from .erase import Erase 5 | from .program import Program 6 | from .passthrough import Passthrough 7 | -------------------------------------------------------------------------------- /NandBugPassthrough.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python3 2 | 3 | from nmigen import * 4 | 5 | from halo import Halo 6 | 7 | from nandbug_platform import NandBugPlatform, NandBugFtdiFIFO 8 | import bitstreams 9 | 10 | 11 | if __name__ == "__main__": 12 | 13 | spinner = Halo( 14 | text="Configuring bitstream for passthrough", spinner="dots") 15 | spinner.start() 16 | 17 | p = NandBugPlatform() 18 | p.build(bitstreams.Passthrough(), do_program=True, 19 | nextpnr_opts="--ignore-loops" # Unfortunatly needed 20 | ) 21 | 22 | fifo = NandBugFtdiFIFO() # Just needed to enable 50MHz clock 23 | 24 | spinner.succeed() 25 | -------------------------------------------------------------------------------- /bitstreams/modules/blinker.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python3 2 | 3 | from nmigen import * 4 | 5 | 6 | class Blinker(Elaboratable): 7 | 8 | def __init__(self, s, period): 9 | """ 10 | Simple blinker module 11 | 12 | Parameters: 13 | s : A signal 14 | period (int): The blink period (seconds) 15 | """ 16 | self.s = s 17 | self.period = period 18 | 19 | def elaborate(self, platform): 20 | m = Module() 21 | 22 | max_value = int(self.period * platform.default_clk_frequency/2 + 1) 23 | 24 | counter = Signal(range(max_value)) 25 | 26 | with m.If(counter == max_value): 27 | m.d.sync += self.s.eq(~self.s) 28 | m.d.sync += counter.eq(0) 29 | with m.Else(): 30 | m.d.sync += counter.eq(counter + 1) 31 | 32 | return m 33 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | # ---> Python 2 | # Byte-compiled / optimized / DLL files 3 | __pycache__/ 4 | *.py[cod] 5 | *$py.class 6 | 7 | # C extensions 8 | *.so 9 | 10 | # Distribution / packaging 11 | .Python 12 | env/ 13 | build/ 14 | develop-eggs/ 15 | dist/ 16 | downloads/ 17 | eggs/ 18 | .eggs/ 19 | lib/ 20 | lib64/ 21 | parts/ 22 | sdist/ 23 | var/ 24 | *.egg-info/ 25 | .installed.cfg 26 | *.egg 27 | 28 | # PyInstaller 29 | # Usually these files are written by a python script from a template 30 | # before PyInstaller builds the exe, so as to inject date/other infos into it. 31 | *.manifest 32 | *.spec 33 | 34 | # Installer logs 35 | pip-log.txt 36 | pip-delete-this-directory.txt 37 | 38 | # Unit test / coverage reports 39 | htmlcov/ 40 | .tox/ 41 | .coverage 42 | .coverage.* 43 | .cache 44 | nosetests.xml 45 | coverage.xml 46 | *,cover 47 | 48 | # Translations 49 | *.mo 50 | *.pot 51 | 52 | # Django stuff: 53 | *.log 54 | 55 | # Sphinx documentation 56 | docs/_build/ 57 | 58 | # PyBuilder 59 | target/ 60 | 61 | *.bin 62 | .venv/ 63 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | MIT License 2 | 3 | Copyright (c) 2020 courk 4 | 5 | Permission is hereby granted, free of charge, to any person obtaining a copy 6 | of this software and associated documentation files (the "Software"), to deal 7 | in the Software without restriction, including without limitation the rights 8 | to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 9 | copies of the Software, and to permit persons to whom the Software is 10 | furnished to do so, subject to the following conditions: 11 | 12 | The above copyright notice and this permission notice shall be included in all 13 | copies or substantial portions of the Software. 14 | 15 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 16 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 17 | FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 18 | AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 19 | LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 20 | OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE 21 | SOFTWARE. 22 | -------------------------------------------------------------------------------- /NandBugDumper.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python3 2 | 3 | import argparse 4 | 5 | from halo import Halo 6 | 7 | from nandbug_platform import NandBugPlatform, NandBugFtdiFIFO 8 | import bitstreams 9 | 10 | 11 | if __name__ == "__main__": 12 | 13 | parser = argparse.ArgumentParser(description="Dump the nand flash content") 14 | parser.add_argument("filename", help="output filename") 15 | args = parser.parse_args() 16 | 17 | spinner = Halo(text="Configuring bitstream for dumping", spinner="dots") 18 | spinner.start() 19 | 20 | p = NandBugPlatform() 21 | p.build(bitstreams.Dump(), do_program=True) 22 | 23 | spinner.succeed() 24 | 25 | spinner = Halo( 26 | text=f"Dumping flash to {args.filename} (0 %)", spinner="dots") 27 | spinner.start() 28 | 29 | fifo = NandBugFtdiFIFO() 30 | 31 | f = open(args.filename, "wb") 32 | total_size = 0 33 | 34 | while total_size != 0x11000000: 35 | 36 | data = fifo.read(256) 37 | 38 | if data: 39 | f.write(data) 40 | total_size += len(data) 41 | 42 | if total_size % (128 * 1024): 43 | percent = int(total_size / 0x11000000 * 100) 44 | spinner.text = f"Dumping flash to {args.filename} " + \ 45 | f"({percent} %)" 46 | 47 | f.close() 48 | spinner.succeed() 49 | -------------------------------------------------------------------------------- /bitstreams/passthrough.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python3 2 | 3 | from nmigen import * 4 | 5 | from .modules import * 6 | 7 | 8 | class Passthrough(Elaboratable): 9 | 10 | def __init__(self): 11 | pass 12 | 13 | def elaborate(self, platform): 14 | 15 | m = Module() 16 | 17 | # 18 | # Passthrough 19 | # 20 | io_cpu = platform.request("io_cpu", 0) 21 | io_nand = platform.request("io_nand", 0) 22 | 23 | cpu_detect = platform.request("cpu_detect") 24 | 25 | # src -> dst 26 | ctrl_signals = {} 27 | for signal in ["wp", "ale", "ce", "we", "re", "cle"]: 28 | ctrl_signals[signal] = (platform.request(f"{signal}_cpu"), 29 | platform.request(f"{signal}_nand")) 30 | 31 | ctrl_signals["ryby"] = (platform.request("ryby_nand"), 32 | platform.request("ryby_cpu")) 33 | 34 | for signal in ctrl_signals: 35 | src, dst = ctrl_signals[signal] 36 | m.d.comb += dst.eq(src) 37 | 38 | m.d.comb += io_cpu.o.eq(io_nand.i) 39 | m.d.comb += io_nand.o.eq(io_cpu.i) 40 | 41 | with m.If(((ctrl_signals["we"][0] == 0) | (io_nand.oe == 1)) 42 | & (ctrl_signals["re"][0] == 1)): 43 | m.d.comb += io_nand.oe.eq(1) 44 | 45 | with m.If(((ctrl_signals["re"][0] == 0) | (io_nand.oe == 0)) 46 | & (ctrl_signals["we"][0] == 1)): 47 | m.d.comb += io_nand.oe.eq(0) 48 | 49 | m.d.comb += io_cpu.oe.eq(~io_nand.oe) 50 | 51 | # 52 | # Status LED Module 53 | # 54 | blink_led = platform.request("led", 0) 55 | blinker = Blinker(blink_led, 0.5) 56 | m.submodules += blinker 57 | 58 | act_led = platform.request("led", 1) 59 | m.d.comb += act_led.eq(~io_nand.oe) 60 | 61 | cpu_led = platform.request("led", 2) 62 | m.d.comb += cpu_led.eq(~cpu_detect) 63 | 64 | return m 65 | -------------------------------------------------------------------------------- /bitstreams/modules/ftdi_fifo.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python3 2 | 3 | from nmigen import * 4 | from nmigen.lib.fifo import AsyncFIFO, SyncFIFO 5 | 6 | 7 | class FtdiFifo(Elaboratable): 8 | """ 9 | FTDI FIFO Interface, to be used with a FTDI in Sync FIFO Mode 10 | 11 | Attributes 12 | ---------- 13 | tx_buffer : SyncFIFO 14 | FIFO containing data to be written to the FTDI 15 | rx_buffer : SyncFIFO 16 | FIFO containing data read from the FTDI 17 | """ 18 | 19 | def __init__(self): 20 | self.tx_buffer = SyncFIFO(width=8, depth=16) 21 | self.rx_buffer = SyncFIFO(width=8, depth=16) 22 | 23 | def elaborate(self, platform): 24 | 25 | m = Module() 26 | 27 | # Register tx and rx fifo as submodules 28 | m.submodules += self.tx_buffer 29 | m.submodules += self.rx_buffer 30 | 31 | # External signals 32 | txe = platform.request("ftdi_txe") 33 | wr = platform.request("ftdi_wr") 34 | rxf = platform.request("ftdi_rxf") 35 | oe = platform.request("ftdi_oe") 36 | rd = platform.request("ftdi_rd") 37 | data = platform.request("ftdi_data") 38 | 39 | write_operation = Signal() 40 | oe_ready = Signal() 41 | 42 | # Set data bus direction 43 | with m.If(write_operation): 44 | m.d.comb += [data.oe.eq(1), oe.eq(1)] 45 | m.d.sync += oe_ready.eq(0) # Add one delay cycle 46 | with m.Else(): 47 | m.d.comb += [data.oe.eq(0), oe.eq(0)] 48 | m.d.sync += oe_ready.eq(1) # Add one delay cycle 49 | 50 | # Manage "write to FTDI" operations 51 | with m.If((txe == 0) & (self.tx_buffer.r_rdy)): 52 | m.d.comb += [write_operation.eq(1), 53 | wr.eq(0), 54 | self.tx_buffer.r_en.eq(1), 55 | data.o.eq(self.tx_buffer.r_data)] 56 | with m.Else(): 57 | m.d.comb += [wr.eq(1), 58 | self.tx_buffer.r_en.eq(0)] 59 | 60 | # Manage "Read from FTDI" operations 61 | with m.If((rxf == 0) & (self.rx_buffer.w_rdy) 62 | & (~write_operation) & oe_ready): 63 | m.d.comb += [rd.eq(0), 64 | self.rx_buffer.w_en.eq(1), 65 | self.rx_buffer.w_data.eq(data.i)] 66 | with m.Else(): 67 | m.d.comb += [rd.eq(1), 68 | self.rx_buffer.w_en.eq(0)] 69 | 70 | return m 71 | -------------------------------------------------------------------------------- /nandbug_platform/nand_bug_platform.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python3 2 | 3 | from nmigen.build import * 4 | from nmigen.vendor.lattice_ice40 import * 5 | from nmigen_boards.resources import * 6 | 7 | from .ice_ftdi import NandBugFtdiProgrammer 8 | 9 | 10 | __all__ = ["NandBugPlatform"] 11 | 12 | 13 | class NandBugPlatform(LatticeICE40Platform): 14 | device = "iCE40HX1K" 15 | package = "TQ144" 16 | default_clk = "clk60" 17 | resources = [ 18 | Resource("clk60", 0, Pins("49", dir="i"), 19 | Clock(60e6), Attrs(GLOBAL=True, IO_STANDARD="SB_LVCMOS")), 20 | 21 | *LEDResources(pins="10 11 12", attrs=Attrs(IO_STANDARD="SB_LVCMOS")), 22 | 23 | Resource("io_cpu", 0, Pins( 24 | "136 137 135 134 138 139 128 129", dir="io")), 25 | Resource("io_nand", 0, Pins("22 23 24 25 31 29 28 26", dir="io")), 26 | 27 | Resource("wp_cpu", 0, Pins("118", dir="i")), 28 | Resource("ale_cpu", 0, Pins("119", dir="i")), 29 | Resource("ce_cpu", 0, Pins("141", dir="i")), 30 | Resource("we_cpu", 0, Pins("142", dir="i")), 31 | Resource("re_cpu", 0, Pins("117", dir="i")), 32 | Resource("cle_cpu", 0, Pins("122", dir="i")), 33 | Resource("ryby_cpu", 0, Pins("143", dir="o")), 34 | 35 | Resource("wp_nand", 0, Pins("2", dir="o")), 36 | Resource("ale_nand", 0, Pins("8", dir="o")), 37 | Resource("ce_nand", 0, Pins("4", dir="o")), 38 | Resource("we_nand", 0, Pins("3", dir="o")), 39 | Resource("re_nand", 0, Pins("7", dir="o")), 40 | Resource("cle_nand", 0, Pins("9", dir="o")), 41 | Resource("ryby_nand", 0, Pins("1", dir="i"), Attrs(PULLUP=1)), 42 | 43 | Resource("cpu_detect", 0, Pins("144", dir="i")), 44 | 45 | Resource("ftdi_data", 0, Pins("62 61 60 58 56 52 50 48", dir="io")), 46 | Resource("ftdi_oe", 0, Pins("41", dir="o")), 47 | Resource("ftdi_siwua", 0, Pins("42", dir="o")), 48 | Resource("ftdi_wr", 0, Pins("43", dir="o")), 49 | Resource("ftdi_rd", 0, Pins("44", dir="o")), 50 | Resource("ftdi_txe", 0, Pins("45", dir="i")), 51 | Resource("ftdi_rxf", 0, Pins("47", dir="i")), 52 | ] 53 | 54 | connectors = [] 55 | 56 | def toolchain_program(self, products, name): 57 | bitstream_data = products.get(f"{name}.bin") 58 | prog = NandBugFtdiProgrammer() 59 | prog.program(bitstream_data) 60 | prog.close() 61 | 62 | 63 | if __name__ == "__main__": 64 | from nmigen_boards.test.blinky import * 65 | NandBugPlatform().build(Blinky(), do_program=True) 66 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # The NandBug Software 2 | 3 | ## Overview 4 | 5 | This software is part of the *NandBug* Project. Hardware files are available [here](https://github.com/courk/NandBug-Hardware). 6 | 7 | *NandBug* is a small FPGA based board that I used in my [Running Custom Code on a Google Home Mini](https://courk.cc/running-custom-code-google-home-mini-part1) project. 8 | 9 | The goal of *NandBug* is to make the NAND Flash of a *Google Home Mini* *In-System Programmable*. 10 | 11 | You can refer to the article for more background information and details. 12 | 13 | ## Dumping the Flash 14 | 15 | `NandBugDumper.py` is used to dump the NAND Flash content. 16 | 17 | ```text 18 | ./NandBugDumper.py -h 19 | usage: NandBugDumper.py [-h] filename 20 | 21 | Dump the nand flash content 22 | 23 | positional arguments: 24 | filename output filename 25 | 26 | optional arguments: 27 | -h, --help show this help message and exit 28 | ``` 29 | 30 | This script will: 31 | 32 | - Generate a *Dump* bitstream and upload it to the FPGA. 33 | - Receive the NAND Flash data and write it to the output `filename`. 34 | 35 | ## Programming the Flash 36 | 37 | `NandBugPatcher.py` is used to alter the NAND Flash content. 38 | 39 | ```text 40 | ./NandBugPatcher.py -h 41 | usage: NandBugPatcher.py [-h] [--last-dump LAST_DUMP] filename 42 | 43 | Patch the nand flash content 44 | 45 | positional arguments: 46 | filename input filename 47 | 48 | optional arguments: 49 | -h, --help show this help message and exit 50 | --last-dump LAST_DUMP 51 | use this dump instead of reading the flash content 52 | ``` 53 | 54 | This script will: 55 | 56 | - Generate a *Dump* bitstream and upload it to the FPGA. 57 | - Receive the NAND Flash data and compare it to the content of `filename`. 58 | - Generate a list of blocks to erase and pages to program. This step can optionally be skipped if a `LAST_DUMP` file is provided. 59 | - Generate a *Erase Blocks* bitstream & upload it to the FPGA. 60 | - Send a list of blocks to erase to the FPGA. 61 | - Generate a *Program Pages* bitstream & upload it to the FPGA. 62 | - Send the pages addresses and data to the FPGA. 63 | 64 | ## Passthrough 65 | 66 | The `NandBugPassthrough.py` script will simply generate a *Passthrough* bitstream and upload it to the FPGA. 67 | 68 | Effectively, this makes the NAND Flash directly connected to the *Google Home Mini*. 69 | 70 | ## Technical Details 71 | 72 | - [nMigen](https://github.com/nmigen/nmigen) is used to generate bitstreams uploaded in the FPGA of *NandBug*. 73 | - [pylibftdi](https://pylibftdi.readthedocs.io/en/0.15.0/) is used for configuring and communicating with *NandBug*. 74 | - [bchlib](https://pypi.org/project/bchlib/) is used to perform error correction. 75 | - For now, the code is very specific to the NAND Flash and *SoC* used by the *Google Home Mini* (memory size and layout, *ECC* scheme, ...) and shouldn't be used with anything else without a couple of modifications. 76 | - Please note it's my first time using *nMigen* in a real project, so the code is likely suboptimal. A known issue is the absence of reliable testbenches for the HDL modules. 77 | -------------------------------------------------------------------------------- /nandbug_platform/ice_ftdi/ice_ftdi.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python3 2 | 3 | import time 4 | import pylibftdi as ftdi 5 | 6 | 7 | __all__ = ["NandBugFtdiProgrammer", "NandBugFtdiFIFO"] 8 | 9 | 10 | class NandBugFtdiProgrammer(object): 11 | """ 12 | Configure a iCE40 FPGA in SPI slave mode 13 | based on iCE40ProgrammingandConfiguration.pdf 14 | """ 15 | 16 | SPI_SCK = (1 << 0) 17 | SPI_SI = (1 << 1) 18 | SPI_SO = (1 << 2) 19 | SPI_SS = (1 << 3) 20 | CRESET_B = (1 << 4) 21 | CDONE = (1 << 5) 22 | 23 | def __init__(self): 24 | deva = ftdi.Device(interface_select=ftdi.INTERFACE_A) 25 | deva.ftdi_fn.ftdi_set_bitmode(0x00, 0x00) # reset 26 | deva.close() 27 | 28 | self.dev = ftdi.Device(interface_select=ftdi.INTERFACE_B) 29 | self.dev.ftdi_fn.ftdi_set_bitmode(0x00, 0x00) # reset 30 | self.dev.ftdi_fn.ftdi_set_bitmode(0x03, 0x02) # MPSSE mode 31 | self.set_spi_clock(500e3) 32 | 33 | def set_spi_clock(self, hz): 34 | div = int((12000000 / (hz * 2)) - 1) 35 | self.ft_write((0x86, div % 256, div // 256)) 36 | 37 | def ft_write(self, data): 38 | s = bytes(data) 39 | ret = self.dev.write(s) 40 | return ret 41 | 42 | def ft_write_cmd_bytes(self, cmd, data): 43 | n = len(data) - 1 44 | self.ft_write([cmd, n % 256, n // 256] + list(data)) 45 | 46 | def ft_read(self, nbytes): 47 | s = self.dev.read(nbytes) 48 | return s 49 | 50 | def program(self, bitstream): 51 | # Set SPI_SCK, SPI_SI, CRESET_B and SPI_SS as output low 52 | output_mask = self.SPI_SCK | self.SPI_SI | self.CRESET_B | self.SPI_SS 53 | self.ft_write((0x80, self.SPI_SCK, output_mask)) 54 | 55 | # Wait for 200us 56 | time.sleep(200e-6) 57 | 58 | # CRESET_B = 1 59 | self.ft_write((0x80, self.CRESET_B, output_mask)) 60 | 61 | # Wait for 1200us 62 | time.sleep(1200e-6) 63 | 64 | # SPI_SS = 1 65 | self.ft_write((0x80, self.SPI_SS | self.CRESET_B, output_mask)) 66 | 67 | # send dummy byte 68 | self.ft_write_cmd_bytes(0x11, b"\xff") 69 | 70 | # SPI_SS = 0 71 | self.ft_write((0x80, self.CRESET_B, output_mask)) 72 | 73 | # Send bitsteam 74 | self.ft_write_cmd_bytes(0x11, bitstream) 75 | 76 | # SPI_SS = 1 77 | self.ft_write((0x80, self.SPI_SS | self.CRESET_B, output_mask)) 78 | 79 | # Wait for 100 clocks 80 | self.ft_write_cmd_bytes(0x11, b"\xff" * 7) 81 | 82 | # Make sure CDONE=1 83 | self.ft_write((0x81,)) 84 | ret = b"" 85 | while not len(ret): 86 | ret = self.ft_read(1) 87 | if not ret[0] & self.CDONE: 88 | raise Exception("CDONE=0") 89 | 90 | # at least 49 more clocks 91 | self.ft_write_cmd_bytes(0x11, b"\xff" * 7) 92 | 93 | def close(self): 94 | self.dev.close() 95 | 96 | 97 | class NandBugFtdiFIFO(object): 98 | """ 99 | Communicate with a FT2232H in Sync FIFO Mode 100 | """ 101 | 102 | def __init__(self): 103 | self.dev = ftdi.Device(interface_select=ftdi.INTERFACE_A) 104 | self.dev.ftdi_fn.ftdi_set_latency_timer(8) 105 | self.dev.ftdi_fn.ftdi_set_bitmode(0x00, 0x00) # reset 106 | self.dev.ftdi_fn.ftdi_set_bitmode(0x02, 0x40) # Sync FIFO mode 107 | 108 | def read(self, n=1): 109 | return self.dev.read(n) 110 | 111 | def write(self, data): 112 | return self.dev.write(data) 113 | 114 | def close(self): 115 | self.dev.close() 116 | -------------------------------------------------------------------------------- /bitstreams/modules/nand_fsm.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python3 2 | 3 | from enum import Enum 4 | 5 | from nmigen import * 6 | from nmigen.back import pysim 7 | 8 | 9 | class WriteType(Enum): 10 | CMD = 0 11 | ADDR = 1 12 | DATA = 2 13 | 14 | 15 | class NandFSM(Elaboratable): 16 | """ 17 | NAND FSM Implementation, used to drive a NAND Flash bus 18 | 19 | Attributes 20 | ---------- 21 | busy : Signal 22 | FSM is busy when equals to '1' 23 | i_data : Signal 24 | Data to write on the bus 25 | o_data : Signal 26 | Data read on the bus 27 | send_cmd : Signal 28 | Set to '1' if data to be sent is a command 29 | send_address : Signal 30 | Set to '1' if data to be sent is an address 31 | send_data : Signal 32 | Set to '1' if data to be sent is data 33 | read_data : Signal 34 | Set to '1' to request a data read 35 | """ 36 | 37 | def __init__(self): 38 | 39 | # Control signals 40 | self.busy = Signal(reset=1) 41 | self.i_data = Signal(8) 42 | self.o_data = Signal(8) 43 | self.send_cmd = Signal() 44 | self.send_address = Signal() 45 | self.send_data = Signal() 46 | self.read = Signal() 47 | 48 | def elaborate(self, platform): 49 | 50 | m = Module() 51 | 52 | # External signals 53 | io_nand = platform.request("io_nand", 0) 54 | self.io_o = io_nand.o 55 | self.io_i = io_nand.i 56 | self.io_oe = io_nand.oe 57 | 58 | self.we = platform.request("we_nand", 0) 59 | self.re = platform.request("re_nand", 0) 60 | self.cle = platform.request("cle_nand", 0) 61 | self.ale = platform.request("ale_nand", 0) 62 | self.ce = platform.request("ce_nand", 0) 63 | self.ryby = platform.request("ryby_nand", 0) 64 | 65 | # Internal signals 66 | i_data_buff = Signal(8) 67 | write_type = Signal(2) 68 | 69 | # Keep the NAND activated 70 | m.d.comb += self.ce.eq(0) 71 | 72 | # 73 | # Main FSM 74 | # 75 | with m.FSM() as fsm: 76 | 77 | with m.State("IDLE"): 78 | with m.If(self.ryby): # Make sure the NAND Flash is ready 79 | 80 | # Check which command to run 81 | with m.If(self.send_data): 82 | m.d.sync += [write_type.eq(WriteType.DATA), 83 | self.ale.eq(0), 84 | self.cle.eq(0)] 85 | m.next = "WRITE" 86 | 87 | with m.Elif(self.send_cmd): 88 | m.d.sync += [write_type.eq(WriteType.CMD), 89 | self.ale.eq(0)] 90 | m.next = "WRITE" 91 | 92 | with m.Elif(self.send_address): 93 | m.d.sync += [write_type.eq(WriteType.ADDR), 94 | self.cle.eq(0)] 95 | m.next = "WRITE" 96 | 97 | with m.Elif(self.read): 98 | m.d.sync += [self.cle.eq(0), 99 | self.ale.eq(0)] 100 | m.next = "READ" 101 | 102 | with m.Else(): 103 | m.d.sync += [self.cle.eq(0), self.ale.eq(0)] 104 | 105 | with m.Else(): 106 | m.d.sync += [self.cle.eq(0), self.ale.eq(0)] 107 | 108 | # When IDLE, keep we and re high & keep busy up 109 | # to date 110 | m.d.comb += self.busy.eq(self.ryby == 0) 111 | m.d.sync += [self.we.eq(1), self.re.eq(1)] 112 | 113 | # Sample input data 114 | m.d.sync += i_data_buff.eq(self.i_data) 115 | 116 | with m.State("WRITE"): 117 | # Write data to the bus 118 | m.d.sync += [self.io_o.eq(i_data_buff), 119 | self.we.eq(0), 120 | self.io_oe.eq(1)] 121 | 122 | # Set cle or ale if necessary 123 | with m.Switch(write_type): 124 | with m.Case(WriteType.CMD): 125 | m.d.sync += self.cle.eq(1) 126 | with m.Case(WriteType.ADDR): 127 | m.d.sync += self.ale.eq(1) 128 | 129 | m.next = "WRITE_HOLD" 130 | 131 | with m.State("WRITE_HOLD"): 132 | m.d.sync += [self.we.eq(1)] 133 | m.next = "IDLE" 134 | 135 | with m.State("READ"): 136 | m.d.sync += [self.re.eq(0), 137 | self.io_oe.eq(0)] 138 | m.next = "READ_SAMPLE" 139 | 140 | with m.State("READ_SAMPLE"): 141 | m.d.sync += [self.o_data.eq(self.io_i), 142 | self.re.eq(1)] 143 | m.next = "IDLE" 144 | 145 | return m 146 | -------------------------------------------------------------------------------- /bitstreams/erase.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python3 2 | 3 | from nmigen import * 4 | 5 | from .modules import * 6 | 7 | 8 | class Erase(Elaboratable): 9 | 10 | def __init__(self): 11 | pass 12 | 13 | def elaborate(self, platform): 14 | 15 | m = Module() 16 | 17 | # 18 | # Status LED Module 19 | # 20 | blink_led = platform.request("led", 0) 21 | blinker = Blinker(blink_led, 0.5) 22 | m.submodules += blinker 23 | 24 | # 25 | # FTDI FIFO Module 26 | # 27 | ftdi_fifo = FtdiFifo() 28 | m.submodules += ftdi_fifo 29 | 30 | # 31 | # NAND FSM Module 32 | # 33 | nand_fsm = NandFSM() 34 | m.submodules += nand_fsm 35 | 36 | # 37 | # Internal signals 38 | # 39 | page_address = Array([Signal(8) for _ in range(3)]) 40 | 41 | # Multi-purpose counter, large enough 42 | # to count bytes in a page 43 | counter = Signal(range(0, 2177)) 44 | 45 | # 46 | # Erase blocks state machine 47 | # 48 | with m.FSM() as fsm: 49 | 50 | # 51 | # RESET the NAND Flash to a clean state 52 | # 53 | 54 | with m.State("RESET"): 55 | with m.If(~nand_fsm.busy): 56 | # Send RESET command (0xFF) 57 | m.d.sync += nand_fsm.i_data.eq(0xFF) 58 | m.d.sync += nand_fsm.send_cmd.eq(1) 59 | m.d.sync += counter.eq(0) 60 | m.next = "WAIT_RESET" 61 | 62 | with m.State("WAIT_RESET"): 63 | m.d.sync += nand_fsm.send_cmd.eq(0) 64 | with m.If(counter == 500): 65 | m.next = "READ_ADDR" 66 | m.d.sync += counter.eq(0) 67 | with m.Else(): 68 | m.d.sync += counter.eq(counter + 1) 69 | 70 | # 71 | # Read address from FTDI FIFO 72 | # 73 | 74 | with m.State("READ_ADDR"): 75 | with m.If(counter != 3): 76 | with m.If(ftdi_fifo.rx_buffer.r_rdy): 77 | m.d.sync += page_address[counter].eq( 78 | ftdi_fifo.rx_buffer.r_data) 79 | m.d.comb += ftdi_fifo.rx_buffer.r_en.eq(1) 80 | m.d.sync += counter.eq(counter+1) 81 | with m.Else(): 82 | m.d.sync += counter.eq(0) 83 | m.next = "CMD1" 84 | 85 | # 86 | # Send the block erase command 87 | # 88 | 89 | with m.State("CMD1"): 90 | # Start by sending the 0x60 CMD 91 | with m.If(~nand_fsm.busy): 92 | m.d.sync += nand_fsm.i_data.eq(0x60) 93 | m.d.sync += nand_fsm.send_cmd.eq(1) 94 | m.d.sync += counter.eq(0) 95 | m.next = "ADDR" 96 | 97 | with m.State("ADDR"): 98 | # Send the 3 bytes of the address 99 | m.d.sync += nand_fsm.send_cmd.eq(0) 100 | with m.If(~nand_fsm.busy): 101 | with m.If(counter < 3): 102 | m.d.sync += nand_fsm.i_data.eq(page_address[counter]) 103 | m.d.sync += nand_fsm.send_address.eq(1) 104 | m.d.sync += counter.eq(counter+1) 105 | m.next = "ADDR" 106 | with m.Else(): 107 | m.d.sync += nand_fsm.send_address.eq(0) 108 | m.next = "CMD2" 109 | 110 | with m.State("CMD2"): 111 | # Finish with the 0xD0 CMD 112 | with m.If(~nand_fsm.busy): 113 | m.d.sync += nand_fsm.i_data.eq(0xD0) 114 | m.d.sync += nand_fsm.send_cmd.eq(1) 115 | m.d.sync += counter.eq(0) 116 | m.next = "WAIT" 117 | 118 | with m.State("WAIT"): 119 | m.d.sync += nand_fsm.send_cmd.eq(0) 120 | with m.If(counter == 500): 121 | with m.If(~nand_fsm.busy): 122 | m.next = "SEND_ADDR" 123 | m.d.sync += counter.eq(0) 124 | with m.Else(): 125 | m.d.sync += counter.eq(counter + 1) 126 | 127 | # 128 | # Send back the address to FTDI FIFO 129 | # (acknowledge the erase command) 130 | # and loop back 131 | # 132 | 133 | with m.State("SEND_ADDR"): 134 | with m.If(counter != 3): 135 | with m.If(ftdi_fifo.tx_buffer.w_rdy): 136 | m.d.comb += ftdi_fifo.tx_buffer.w_data.eq( 137 | page_address[counter]) 138 | m.d.comb += ftdi_fifo.tx_buffer.w_en.eq(1) 139 | m.d.sync += counter.eq(counter+1) 140 | with m.Else(): 141 | m.d.sync += counter.eq(0) 142 | m.next = "READ_ADDR" 143 | 144 | with m.State("IDLE"): 145 | pass 146 | 147 | return m 148 | -------------------------------------------------------------------------------- /NandBugPatcher.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python3 2 | 3 | import argparse 4 | import tempfile 5 | import struct 6 | 7 | from halo import Halo 8 | 9 | import bchlib 10 | 11 | from nandbug_platform import NandBugPlatform, NandBugFtdiFIFO 12 | import bitstreams 13 | 14 | 15 | def nibble_swap(data): 16 | result = bytearray() 17 | for c in data: 18 | result.append(((c & 0x0F) << 4) | ((c & 0xF0) >> 4)) 19 | return result 20 | 21 | 22 | def ecc_fix(infilename, outfilename): 23 | data = open(infilename, "rb").read() 24 | 25 | bch = bchlib.BCH(0x8003, 48) 26 | 27 | f = open(outfilename, "wb") 28 | 29 | total_flips = 0 30 | for offset in range(len(data)//0x880): 31 | page = data[offset*0x880:(offset+1)*0x880] 32 | page_data = nibble_swap(page[:0x820]) 33 | page_ecc = nibble_swap(page[0x820:-6]) 34 | page_padding = page[-6:] 35 | flips = bch.decode_inplace(page_data, page_ecc) 36 | if flips > 0: 37 | total_flips += flips 38 | f.write(nibble_swap(page_data) + nibble_swap(page_ecc) + page_padding) 39 | 40 | f.close() 41 | 42 | return total_flips 43 | 44 | 45 | def get_modified_blocks(before_filename, after_filename): 46 | before_data = open(before_filename, "rb").read() 47 | after_data = open(after_filename, "rb").read() 48 | 49 | modified_blocks = [] 50 | 51 | for page_index in range(0, len(before_data)//0x880): 52 | before_page = before_data[page_index*0x880:(page_index+1)*0x880] 53 | after_page = after_data[page_index*0x880:(page_index+1)*0x880] 54 | if before_page != after_page: 55 | block_index = page_index // 64 56 | if block_index not in modified_blocks: 57 | modified_blocks.append(block_index) 58 | 59 | return modified_blocks 60 | 61 | 62 | if __name__ == "__main__": 63 | 64 | parser = argparse.ArgumentParser( 65 | description="Patch the nand flash content") 66 | parser.add_argument("filename", help="input filename") 67 | parser.add_argument( 68 | "--last-dump", 69 | help="use this dump instead of reading the flash content") 70 | args = parser.parse_args() 71 | 72 | with tempfile.TemporaryDirectory() as tmpdir: 73 | if not args.last_dump: 74 | last_dump = f"{tmpdir}/dump.bin" 75 | spinner = Halo( 76 | text="Configuring bitstream for dumping", spinner="dots") 77 | spinner.start() 78 | 79 | p = NandBugPlatform() 80 | p.build(bitstreams.Dump(), do_program=True) 81 | 82 | spinner.succeed() 83 | 84 | spinner = Halo( 85 | text=f"Dumping flash to {last_dump} (0 %)", spinner="dots") 86 | spinner.start() 87 | 88 | fifo = NandBugFtdiFIFO() 89 | 90 | f = open(last_dump, "wb") 91 | total_size = 0 92 | 93 | while total_size != 0x11000000: 94 | data = fifo.read(256) 95 | if data: 96 | f.write(data) 97 | total_size += len(data) 98 | if total_size % (128 * 1024): 99 | percent = int(total_size / 0x11000000 * 100) 100 | spinner.text = f"Dumping flash to {last_dump} " + \ 101 | f"({percent} %)" 102 | 103 | f.close() 104 | fifo.close() 105 | spinner.succeed() 106 | 107 | spinner = Halo(text="Performing error correction", spinner="dots") 108 | spinner.start() 109 | 110 | corrected_filename = f"{tmpdir}/dump_fixed.bin" 111 | 112 | flips = ecc_fix(last_dump, corrected_filename) 113 | spinner.succeed() 114 | 115 | print(f"Corrected {flips} errors") 116 | 117 | last_dump = corrected_filename 118 | 119 | else: 120 | last_dump = args.last_dump 121 | 122 | modified_blocks = get_modified_blocks(last_dump, args.filename) 123 | 124 | if len(modified_blocks) == 0: 125 | print("Nothing to patch") 126 | exit(0) 127 | 128 | print(f"{len(modified_blocks)} blocks will be modified") 129 | 130 | spinner = Halo( 131 | text="Configuring bitstream for erasing blocks", spinner="dots") 132 | spinner.start() 133 | 134 | p = NandBugPlatform() 135 | p.build(bitstreams.Erase(), do_program=True) 136 | 137 | spinner.succeed() 138 | 139 | spinner = Halo(text=f"Erasing blocks", spinner="dots") 140 | spinner.start() 141 | 142 | fifo = NandBugFtdiFIFO() 143 | 144 | for block_index in modified_blocks: 145 | addr = struct.pack("