opentitanlib/spiflash/
flash.rs

1// Copyright lowRISC contributors (OpenTitan project).
2// Licensed under the Apache License, Version 2.0, see LICENSE for details.
3// SPDX-License-Identifier: Apache-2.0
4
5use crate::app::NoProgressBar;
6use crate::io::eeprom::{AddressMode, MODE_111, MODE_112, MODE_114, Mode, Transaction};
7use crate::io::spi::Target;
8use crate::spiflash::sfdp;
9use crate::spiflash::sfdp::{
10    BlockEraseSize, FastReadParam, SectorErase, Sfdp, SupportedAddressModes,
11};
12use crate::transport::ProgressIndicator;
13use anyhow::{Result, ensure};
14use clap::ValueEnum;
15use std::convert::TryFrom;
16use thiserror::Error;
17
18#[derive(Debug, Error)]
19pub enum Error {
20    #[error("address out of bounds: {0} >= {1}")]
21    AddressOutOfBounds(u32, u32),
22    #[error("erase at address {0} not aligned on {1}-byte boundary")]
23    BadEraseAddress(u32, u32),
24    #[error("erase length {0} not a multiple of {1} bytes")]
25    BadEraseLength(u32, u32),
26    #[error("bad sequence length: {0}")]
27    BadSequenceLength(usize),
28    #[error("unsupported mode: {0:?}")]
29    UnsupportedMode(ReadMode),
30    #[error("unsupported opcode: {0:x?}")]
31    UnsupportedOpcode(u8),
32}
33
34impl From<SupportedAddressModes> for AddressMode {
35    fn from(mode: SupportedAddressModes) -> Self {
36        match mode {
37            SupportedAddressModes::Mode4b => AddressMode::Mode4b,
38            _ => AddressMode::Mode3b,
39        }
40    }
41}
42
43#[derive(Debug, Clone, Copy, ValueEnum, Default)]
44#[value(rename_all = "verbatim")]
45pub enum ReadMode {
46    #[default]
47    Standard,
48    Fast,
49    Dual,
50    Quad,
51}
52
53pub struct ReadTypes {
54    pub standard: FastReadParam,
55    pub fast: FastReadParam,
56    pub dual: FastReadParam,
57    pub quad: FastReadParam,
58}
59
60impl Default for ReadTypes {
61    fn default() -> Self {
62        Self {
63            standard: FastReadParam {
64                wait_states: 0,
65                mode_bits: 0,
66                opcode: SpiFlash::READ,
67            },
68            fast: FastReadParam {
69                wait_states: 8,
70                mode_bits: 0,
71                opcode: SpiFlash::FAST_READ,
72            },
73            dual: FastReadParam {
74                wait_states: 8,
75                mode_bits: 0,
76                opcode: SpiFlash::FAST_DUAL_READ,
77            },
78            quad: FastReadParam {
79                wait_states: 8,
80                mode_bits: 0,
81                opcode: SpiFlash::FAST_QUAD_READ,
82            },
83        }
84    }
85}
86
87impl ReadTypes {
88    pub fn from_sfdp(sfdp: &Sfdp) -> Self {
89        Self {
90            standard: FastReadParam {
91                wait_states: 0,
92                mode_bits: 0,
93                opcode: SpiFlash::READ,
94            },
95            fast: FastReadParam {
96                wait_states: 8,
97                mode_bits: 0,
98                opcode: SpiFlash::FAST_READ,
99            },
100            dual: if sfdp.jedec.support_fast_read_112 {
101                sfdp.jedec.param_112.clone()
102            } else {
103                Default::default()
104            },
105            quad: if sfdp.jedec.support_fast_read_114 {
106                sfdp.jedec.param_114.clone()
107            } else {
108                Default::default()
109            },
110        }
111    }
112}
113
114#[derive(Debug, Clone, Copy, PartialEq, Eq, ValueEnum, Default)]
115#[value(rename_all = "verbatim")]
116pub enum EraseMode {
117    #[default]
118    Standard,
119    Block,
120}
121
122pub struct SpiFlash {
123    pub size: u32,
124    pub program_size: u32,
125    pub address_mode: AddressMode,
126    pub read_mode: ReadMode,
127    pub erase_mode: EraseMode,
128    pub sfdp: Option<Sfdp>,
129    pub read_type: ReadTypes,
130    pub erase: Vec<SectorErase>,
131    pub program_ff_optimization: bool,
132}
133
134impl Default for SpiFlash {
135    fn default() -> Self {
136        SpiFlash {
137            size: 16 * 1024 * 1024,
138            program_size: SpiFlash::LEGACY_PAGE_SIZE,
139            address_mode: Default::default(),
140            read_mode: Default::default(),
141            erase_mode: Default::default(),
142            sfdp: None,
143            read_type: Default::default(),
144            erase: vec![SectorErase {
145                size: 4096,
146                opcode: SpiFlash::SECTOR_ERASE,
147                time: None,
148            }],
149            program_ff_optimization: true,
150        }
151    }
152}
153
154impl SpiFlash {
155    // Well known SPI Flash opcodes.
156    pub const READ: u8 = 0x03;
157    pub const FAST_READ: u8 = 0x0b;
158    pub const FAST_DUAL_READ: u8 = 0x3b;
159    pub const FAST_QUAD_READ: u8 = 0x6b;
160    pub const READ_4B: u8 = 0x13;
161    pub const FAST_READ_4B: u8 = 0x0c;
162    pub const FAST_DUAL_READ_4B: u8 = 0x3c;
163    pub const FAST_QUAD_READ_4B: u8 = 0x6c;
164    pub const PAGE_PROGRAM: u8 = 0x02;
165    pub const SECTOR_ERASE: u8 = 0x20;
166    pub const BLOCK_ERASE_32K: u8 = 0x52;
167    pub const BLOCK_ERASE_64K: u8 = 0xD8;
168    pub const SECTOR_ERASE_4B: u8 = 0x21;
169    pub const BLOCK_ERASE_32K_4B: u8 = 0x5C;
170    pub const BLOCK_ERASE_64K_4B: u8 = 0xDC;
171    pub const CHIP_ERASE: u8 = 0xc7;
172    pub const WRITE_ENABLE: u8 = 0x06;
173    pub const WRITE_DISABLE: u8 = 0x04;
174    pub const READ_STATUS: u8 = 0x05;
175    // Winbond parts use 0x35 and 0x15 for extended status reads.
176    pub const READ_STATUS2: u8 = 0x35;
177    pub const READ_STATUS3: u8 = 0x15;
178    pub const WRITE_STATUS: u8 = 0x01;
179    // Winbond parts use 0x31 and 0x11 for extended status writes.
180    pub const WRITE_STATUS2: u8 = 0x31;
181    pub const WRITE_STATUS3: u8 = 0x11;
182    pub const READ_ID: u8 = 0x9f;
183    pub const ENTER_4B: u8 = 0xb7;
184    pub const EXIT_4B: u8 = 0xe9;
185    pub const READ_SFDP: u8 = 0x5a;
186    pub const NOP: u8 = 0x00;
187    pub const RESET_ENABLE: u8 = 0x66;
188    pub const RESET: u8 = 0x99;
189
190    /// The legacy JEDEC page size for programming operations is 256 bytes.
191    pub const LEGACY_PAGE_SIZE: u32 = 256;
192
193    /// Status register bits:
194    /// The `WIP` bit indicates a write in progress (sometimes called the busy bit).
195    pub const STATUS_WIP: u8 = 0x01;
196    /// The `WEL` bit is the write enable latch.
197    pub const STATUS_WEL: u8 = 0x02;
198
199    /// Read `length` bytes of the JEDEC ID from the `spi` target.
200    pub fn read_jedec_id(spi: &dyn Target, length: usize) -> Result<Vec<u8>> {
201        let mut buf = vec![0u8; length];
202        spi.run_eeprom_transactions(&mut [Transaction::Read(
203            MODE_111.cmd(SpiFlash::READ_ID),
204            &mut buf,
205        )])?;
206        Ok(buf)
207    }
208
209    /// Read status register from the `spi` target.
210    pub fn read_status(spi: &dyn Target) -> Result<u8> {
211        let mut buf = [0u8; 1];
212        spi.run_eeprom_transactions(&mut [Transaction::Read(
213            MODE_111.cmd(SpiFlash::READ_STATUS),
214            &mut buf,
215        )])?;
216        Ok(buf[0])
217    }
218
219    /// Read the extended status register from the `spi` target.
220    pub fn read_status_ex(spi: &dyn Target, seq: Option<&[u8]>) -> Result<u32> {
221        let seq = seq.unwrap_or(&[Self::READ_STATUS, Self::READ_STATUS2, Self::READ_STATUS3]);
222        ensure!(
223            !seq.is_empty() && seq.len() <= 3,
224            Error::BadSequenceLength(seq.len())
225        );
226        let mut buf = [0u8; 4];
227        for (op, byte) in seq.iter().zip(buf.iter_mut()) {
228            spi.run_eeprom_transactions(&mut [Transaction::Read(
229                MODE_111.cmd(*op),
230                std::slice::from_mut(byte),
231            )])?;
232        }
233        Ok(u32::from_le_bytes(buf))
234    }
235
236    /// Poll the status register waiting for the busy bit to clear.
237    pub fn wait_for_busy_clear(spi: &dyn Target) -> Result<()> {
238        spi.run_eeprom_transactions(&mut [Transaction::WaitForBusyClear])?;
239        Ok(())
240    }
241
242    /// Send the WRITE_ENABLE opcode to the `spi` target.
243    pub fn set_write_enable(spi: &dyn Target) -> Result<()> {
244        spi.run_eeprom_transactions(&mut [Transaction::Command(
245            MODE_111.cmd(SpiFlash::WRITE_ENABLE),
246        )])?;
247        Ok(())
248    }
249
250    /// Send the WRITE_DISABLE opcode to the `spi` target.
251    pub fn set_write_disable(spi: &dyn Target) -> Result<()> {
252        spi.run_eeprom_transactions(&mut [Transaction::Command(
253            MODE_111.cmd(SpiFlash::WRITE_DISABLE),
254        )])?;
255        Ok(())
256    }
257
258    /// Read and parse the SFDP table from the `spi` target.
259    pub fn read_sfdp(spi: &dyn Target) -> Result<Sfdp> {
260        let mut buf = vec![0u8; 256];
261        let mut tries = 0;
262        loop {
263            // READ_SFDP always takes a 3-byte address followed by a dummy byte regardless of
264            // address mode.
265            let mut eeprom_transactions = Vec::new();
266            let read_size = spi.get_eeprom_max_transfer_sizes()?.read;
267            for (i, transfer) in buf.chunks_mut(read_size).enumerate() {
268                eeprom_transactions.push(Transaction::Read(
269                    MODE_111.dummy_cycles(8).cmd_addr(
270                        SpiFlash::READ_SFDP,
271                        (i * read_size) as u32,
272                        AddressMode::Mode3b,
273                    ),
274                    transfer,
275                ));
276            }
277            spi.run_eeprom_transactions(&mut eeprom_transactions)?;
278
279            // We only want to give SFDP parsing one extra chance for length
280            // extension. If parsing fails a second time, just return the error.
281            let result = Sfdp::try_from(&buf[..]);
282            if result.is_ok() || tries > 0 {
283                return result;
284            }
285            buf.resize(Sfdp::length_required(&buf)?, 0);
286            tries += 1;
287        }
288    }
289
290    /// Check whether the `spi` target responds to READ_SFDP with a valid header.
291    pub fn sfdp_present(spi: &dyn Target) -> Result<bool> {
292        match Self::read_sfdp(spi) {
293            Ok(_) => Ok(true),
294            Err(e) => match e.downcast_ref::<sfdp::Error>() {
295                Some(sfdp::Error::WrongHeaderSignature(_)) => Ok(false),
296                _ => Err(e),
297            },
298        }
299    }
300
301    /// Create a new `SpiFlash` instance from an SFDP table.
302    pub fn from_sfdp(sfdp: Sfdp) -> Self {
303        let read_type = ReadTypes::from_sfdp(&sfdp);
304        let mut erase = sfdp
305            .jedec
306            .erase
307            .iter()
308            .filter_map(|e| if e.size != 0 { Some(e.clone()) } else { None })
309            .collect::<Vec<_>>();
310        // If the SFDP claims to support 4K erases, but a 4K SectorErase is not
311        // present, synthesize one and add it to the list.
312        if sfdp.jedec.block_erase_size == BlockEraseSize::Block4KiB
313            && !erase.iter().any(|e| e.size == 4096)
314        {
315            erase.push(SectorErase {
316                size: 4096,
317                opcode: sfdp.jedec.erase_opcode_4kib,
318                time: None,
319            });
320        }
321        // Sort largest to smallest.
322        erase.sort_by(|a, b| b.size.cmp(&a.size));
323
324        SpiFlash {
325            size: sfdp.jedec.density,
326            program_size: SpiFlash::LEGACY_PAGE_SIZE,
327            address_mode: AddressMode::from(sfdp.jedec.address_modes),
328            read_mode: Default::default(),
329            erase_mode: Default::default(),
330            sfdp: Some(sfdp),
331            read_type,
332            erase,
333            program_ff_optimization: true,
334        }
335    }
336
337    /// Create a new `SpiFlash` instance by reading an SFDP table from the `spi` Target.
338    pub fn from_spi(spi: &dyn Target) -> Result<Self> {
339        let sfdp = SpiFlash::read_sfdp(spi)?;
340        Ok(SpiFlash::from_sfdp(sfdp))
341    }
342
343    /// Set the SPI flash addressing mode to either 3b or 4b mode.
344    pub fn set_address_mode(&mut self, spi: &dyn Target, mode: AddressMode) -> Result<()> {
345        let opcode = match mode {
346            AddressMode::Mode3b => SpiFlash::EXIT_4B,
347            AddressMode::Mode4b => SpiFlash::ENTER_4B,
348        };
349        spi.run_eeprom_transactions(&mut [Transaction::Command(MODE_111.cmd(opcode))])?;
350        self.address_mode = mode;
351        Ok(())
352    }
353
354    /// Automatically set the addressing mode based on the size of the SPI flash.
355    pub fn set_address_mode_auto(&mut self, spi: &dyn Target) -> Result<()> {
356        self.set_address_mode(
357            spi,
358            if self.size <= 16 * 1024 * 1024 {
359                AddressMode::Mode3b
360            } else {
361                AddressMode::Mode4b
362            },
363        )
364    }
365
366    /// Read into `buffer` from the SPI flash starting at `address`.
367    pub fn read(&self, spi: &dyn Target, address: u32, buffer: &mut [u8]) -> Result<&Self> {
368        self.read_with_progress(spi, address, buffer, &NoProgressBar, false)
369    }
370
371    fn select_read(&self) -> Result<(Mode, &FastReadParam)> {
372        match self.read_mode {
373            ReadMode::Standard => Ok((MODE_111, &self.read_type.standard)),
374            ReadMode::Fast => Ok((MODE_111, &self.read_type.fast)),
375            ReadMode::Dual if self.read_type.dual.opcode != 0 => {
376                Ok((MODE_112, &self.read_type.dual))
377            }
378            ReadMode::Quad if self.read_type.quad.opcode != 0 => {
379                Ok((MODE_114, &self.read_type.quad))
380            }
381            _ => Err(Error::UnsupportedMode(self.read_mode).into()),
382        }
383    }
384
385    /// Read into `buffer` from the SPI flash starting at `address`.
386    /// The `progress` callback will be invoked after each chunk of the read operation.
387    pub fn read_with_progress(
388        &self,
389        spi: &dyn Target,
390        mut address: u32,
391        buffer: &mut [u8],
392        progress: &dyn ProgressIndicator,
393        use_4b_opcodes: bool,
394    ) -> Result<&Self> {
395        progress.new_stage("", buffer.len());
396        let (mode, param) = self.select_read()?;
397        let (address_mode, opcode) = if use_4b_opcodes {
398            // If we've been asked to use the 4-byte version of the read opcodes,
399            // map the opcode to its 4b counterpart.
400            (
401                AddressMode::Mode4b,
402                match param.opcode {
403                    SpiFlash::READ => SpiFlash::READ_4B,
404                    SpiFlash::FAST_READ => SpiFlash::FAST_READ_4B,
405                    SpiFlash::FAST_DUAL_READ => SpiFlash::FAST_DUAL_READ_4B,
406                    SpiFlash::FAST_QUAD_READ => SpiFlash::FAST_QUAD_READ_4B,
407                    _ => return Err(Error::UnsupportedOpcode(param.opcode).into()),
408                },
409            )
410        } else {
411            (self.address_mode, param.opcode)
412        };
413        // Break the read up according to the maximum chunksize the backend can handle.
414        let chunk_size = spi.get_eeprom_max_transfer_sizes()?.read;
415        for (idx, chunk) in buffer.chunks_mut(chunk_size).enumerate() {
416            progress.progress(idx * chunk_size);
417            spi.run_eeprom_transactions(&mut [Transaction::Read(
418                mode.dummy_cycles(param.wait_states)
419                    .cmd_addr(opcode, address, address_mode),
420                chunk,
421            )])?;
422            address += chunk.len() as u32;
423        }
424        progress.progress(buffer.len());
425        Ok(self)
426    }
427
428    /// Erase the entire EEPROM via the CHIP_ERASE opcode.
429    pub fn chip_erase(&self, spi: &dyn Target) -> Result<&Self> {
430        spi.run_eeprom_transactions(&mut [
431            Transaction::Command(MODE_111.cmd(SpiFlash::WRITE_ENABLE)),
432            Transaction::Command(MODE_111.cmd(SpiFlash::CHIP_ERASE)),
433            Transaction::WaitForBusyClear,
434        ])?;
435        Ok(self)
436    }
437
438    /// Erase a segment of the SPI flash starting at `address` for `length` bytes.
439    /// The address and length must be sector aligned.
440    pub fn erase(&self, spi: &dyn Target, address: u32, length: u32) -> Result<&Self> {
441        self.erase_with_progress(spi, address, length, &NoProgressBar)
442    }
443
444    fn select_erase(&self, address: u32, length: u32) -> Result<&SectorErase> {
445        if self.erase_mode == EraseMode::Standard {
446            // We assume the last element of the `erase` list is the standard
447            // SECTOR_ERASE.  So far, this has been true for all eeproms
448            // encountered by the author.
449            return Ok(self.erase.last().unwrap());
450        }
451        for e in self.erase.iter() {
452            if address.is_multiple_of(e.size) && length >= e.size {
453                return Ok(e);
454            }
455        }
456        Err(Error::BadEraseAddress(address, self.erase.last().unwrap().size).into())
457    }
458
459    /// Erase a segment of the SPI flash starting at `address` for `length` bytes.
460    /// The address and length must be sector aligned.
461    /// The `progress` callback will be invoked after each chunk of the erase operation.
462    pub fn erase_with_progress(
463        &self,
464        spi: &dyn Target,
465        address: u32,
466        length: u32,
467        progress: &dyn ProgressIndicator,
468    ) -> Result<&Self> {
469        let min_erase_size = self.erase.last().unwrap().size;
470        if !address.is_multiple_of(min_erase_size) {
471            return Err(Error::BadEraseAddress(address, min_erase_size).into());
472        }
473        if !length.is_multiple_of(min_erase_size) {
474            return Err(Error::BadEraseLength(length, min_erase_size).into());
475        }
476        progress.new_stage("", length as usize);
477        let end = address + length;
478        let mut addr = address;
479        while addr < end {
480            let erase = self.select_erase(addr, end - addr)?;
481            spi.run_eeprom_transactions(&mut [
482                Transaction::Command(MODE_111.cmd(SpiFlash::WRITE_ENABLE)),
483                Transaction::Command(MODE_111.cmd_addr(erase.opcode, addr, self.address_mode)),
484                Transaction::WaitForBusyClear,
485            ])?;
486            progress.progress((addr - address) as usize);
487            addr += erase.size;
488        }
489        progress.progress(length as usize);
490        Ok(self)
491    }
492
493    /// Program a segment of the SPI flash starting at `address` with the contents of `buffer`.
494    /// The address and buffer length may be arbitrary.  This function will not
495    /// erase the segment first.
496    pub fn program(&self, spi: &dyn Target, address: u32, buffer: &[u8]) -> Result<&Self> {
497        self.program_with_progress(spi, address, buffer, &NoProgressBar)
498    }
499
500    /// Program a segment of the SPI flash starting at `address` with the contents of `buffer`.
501    /// The address and buffer length may be arbitrary.  This function will not
502    /// erase the segment first.
503    /// The `progress` callback will be invoked after each chunk of the program operation.
504    pub fn program_with_progress(
505        &self,
506        spi: &dyn Target,
507        mut address: u32,
508        buffer: &[u8],
509        progress: &dyn ProgressIndicator,
510    ) -> Result<&Self> {
511        progress.new_stage("", buffer.len());
512        let mut remain = buffer.len();
513        let mut chunk_start = 0usize;
514        while remain != 0 {
515            // If the address isn't program-page-size aligned, adjust the first
516            // chunk so that subsequent writes will be so-aligned.
517            // This is necessary because the SPI eeprom will wrap within the
518            // programming page and the resultant data in the eeprom will not
519            // be what you intended.
520            let chunk_size = (self.program_size - (address % self.program_size)) as usize;
521            let chunk_size = std::cmp::min(chunk_size, remain);
522            let chunk_end = chunk_start + chunk_size;
523            let chunk = &buffer[chunk_start..chunk_end];
524            // Skip this chunk if all bytes are 0xff.
525            if !self.program_ff_optimization || !chunk.iter().all(|&x| x == 0xff) {
526                spi.run_eeprom_transactions(&mut [
527                    Transaction::Command(MODE_111.cmd(SpiFlash::WRITE_ENABLE)),
528                    Transaction::Write(
529                        MODE_111.cmd_addr(SpiFlash::PAGE_PROGRAM, address, self.address_mode),
530                        chunk,
531                    ),
532                    Transaction::WaitForBusyClear,
533                ])?;
534            }
535            address += chunk_size as u32;
536            chunk_start += chunk_size;
537            remain -= chunk_size;
538            progress.progress(buffer.len() - remain);
539        }
540        Ok(self)
541    }
542
543    /// Send the software reset sequence to the `spi` target.
544    pub fn chip_reset(spi: &dyn Target) -> Result<()> {
545        spi.run_eeprom_transactions(&mut [
546            Transaction::Command(MODE_111.cmd(SpiFlash::RESET_ENABLE)),
547            Transaction::Command(MODE_111.cmd(SpiFlash::RESET)),
548        ])?;
549        Ok(())
550    }
551}