Skip to main content

sdmmc_async/
spi.rs

1use embedded_hal_async::delay::DelayNs;
2use embedded_hal_async::spi::{Operation, SpiBus, SpiDevice};
3
4use crate::{BlockDevice, BLOCK_SIZE};
5
6/// What can go wrong talking to a card over SPI. `E` is the SPI device's own error.
7///
8/// New variants may be added in a minor release.
9#[derive(Clone, Copy, Debug, PartialEq, Eq)]
10#[non_exhaustive]
11pub enum SpiError<E> {
12    /// The SPI device failed.
13    Spi(E),
14    /// The card did not answer in time (none fitted, or removed).
15    Timeout,
16    /// The card answered with an unexpected R1 byte or data error token.
17    BadResponse(u8),
18    /// A command response or data block failed its CRC, even after repeating the read.
19    BadCrc,
20    /// The card cannot be used: not an SD card, or its capacity is not readable.
21    UnsupportedCard,
22    /// A block number past the end of the card.
23    OutOfRange,
24    /// The card refused a written block: its data response token (the low five bits), for example a write error (`0x0d`).
25    /// A CRC error is reported as `BadCrc`.
26    WriteRejected(u8),
27}
28
29/// The SD spec allows a card 100 ms to start a read; the poll loop waits at least that long at any clock.
30const READ_TOKEN_POLLS: u32 = 2_000;
31const READ_TOKEN_POLL_US: u32 = 50;
32
33/// Repeats of a data read that failed (see `read_with_data`).
34const READ_RETRIES: usize = 2;
35
36/// Repeats of a block write the card answered with a CRC error.
37#[cfg(feature = "write")]
38const WRITE_RETRIES: usize = 2;
39/// The SD spec allows a card 250 ms to program a block; the busy wait gives it about 500 ms: 64 short polls, then 1 ms ones.
40#[cfg(feature = "write")]
41const WRITE_FAST_POLLS: u32 = 64;
42#[cfg(feature = "write")]
43const WRITE_SLOW_POLLS: u32 = 500;
44
45/// A card answers a command within eight bytes.
46const R1_WINDOW: usize = 8;
47/// How many idle bytes the single-transaction read allows between the R1 and the data token. It starts
48/// at `START_TOKEN_WINDOW` and follows the gap the card actually shows, within these limits.
49const MIN_TOKEN_WINDOW: usize = 32;
50const START_TOKEN_WINDOW: usize = 256;
51const MAX_TOKEN_WINDOW: usize = 2_048;
52const SCRATCH: usize = R1_WINDOW + MAX_TOKEN_WINDOW + 1 + BLOCK_SIZE + 2;
53
54/// The card must see at least 74 clock cycles with chip select high before its first command. A
55/// `SpiDevice` always asserts chip select, so call this on the raw bus (at 400 kHz or less) before
56/// wrapping it into the device handed to `SpiSdCard::new`.
57pub async fn send_init_clocks<B: SpiBus<u8>>(bus: &mut B) -> Result<(), B::Error> {
58    bus.write(&[0xff; 10]).await?;
59    bus.flush().await
60}
61
62/// An SD card behind a `SpiDevice`, so the bus can be shared with other devices. Every device on a
63/// shared bus keeps its own clock and mode in its own `SpiDevice`; this driver never touches the bus
64/// configuration. The card is read-only unless the `write` feature is on.
65///
66/// The SD spec wants chip select low from the command through the data block. A read is therefore
67/// one transaction: the command frame, a window for the R1 and the idle bytes before the data token,
68/// and the block with its CRC. The window follows the gap the card shows (it clocks the whole window
69/// every time, so it stays as small as the card allows). If the token has not arrived when the window
70/// ends, the read falls back to polling for it with chip select released between polls, which a card
71/// that aborts on chip select rising will fail; the window then grows, so a retry takes the single
72/// transaction path.
73///
74/// The `SpiDevice` must be at a clock of 400 kHz or less for `new`, and can be raised afterwards
75/// through `spi_mut`. A card's MISO driver can take a clock edge to let go of the line after chip
76/// select rises, so on a bus shared with a device that is selected right afterwards the first bit it
77/// sends can be corrupted; give the card its own bus if that matters.
78pub struct SpiSdCard<SPI, D> {
79    spi: SPI,
80    delay: D,
81    high_capacity: bool,
82    blocks: u32,
83    check_crc: bool,
84    token_window: usize,
85    scratch: [u8; SCRATCH],
86}
87
88#[derive(Clone, Copy)]
89enum Reply {
90    R1,
91    R1WithFourBytes,
92}
93
94#[derive(Clone, Copy)]
95struct Response {
96    r1: u8,
97    extra: [u8; 4],
98}
99
100impl<SPI, D> SpiSdCard<SPI, D>
101where
102    SPI: SpiDevice<u8>,
103    D: DelayNs,
104{
105    /// Initialises the card: resets it, negotiates SDHC/SDXC, turns on CRCs and reads its size. The `SpiDevice` must be at
106    /// 400 kHz or less, and the card must already have had its 74 init clocks (see `send_init_clocks`).
107    pub async fn new(spi: SPI, delay: D) -> Result<Self, SpiError<SPI::Error>> {
108        Self::init(spi, delay).await.map_err(|(_, error)| error)
109    }
110
111    /// `new`, giving the SPI device back when the card does not initialise (none fitted, a bad card), so the caller can
112    /// try again.
113    #[allow(clippy::type_complexity)]
114    pub async fn init(spi: SPI, delay: D) -> Result<Self, (SPI, SpiError<SPI::Error>)> {
115        let mut card = Self {
116            spi,
117            delay,
118            high_capacity: false,
119            blocks: 0,
120            check_crc: false,
121            token_window: START_TOKEN_WINDOW,
122            scratch: [0xff; SCRATCH],
123        };
124        match card.initialise().await {
125            Ok(()) => Ok(card),
126            Err(error) => Err((card.spi, error)),
127        }
128    }
129
130    async fn initialise(&mut self) -> Result<(), SpiError<SPI::Error>> {
131        self.delay.delay_ms(1).await;
132
133        // CMD0 is the one command a marginal card often misses. Retry it before
134        // giving up, and keep the final Timeout rather than turning it into a
135        // misleading bad response.
136        let mut r1 = 0xff;
137        let mut timed_out = false;
138        for _ in 0..10 {
139            match self.command(0, 0, Reply::R1).await {
140                Ok(response) if response.r1 == 0x01 => {
141                    r1 = 0x01;
142                    break;
143                }
144                Ok(response) => {
145                    r1 = response.r1;
146                    timed_out = false;
147                }
148                Err(SpiError::Timeout) => {
149                    r1 = 0xff;
150                    timed_out = true;
151                }
152                Err(error) => return Err(error),
153            }
154            self.delay.delay_ms(1).await;
155        }
156        if r1 != 0x01 {
157            return Err(if timed_out {
158                SpiError::Timeout
159            } else {
160                SpiError::BadResponse(r1)
161            });
162        }
163
164        let interface = self.command(8, 0x1aa, Reply::R1WithFourBytes).await?;
165        let version_2 = interface.r1 & 0x04 == 0;
166        if version_2 && (interface.r1 != 0x01 || interface.extra != [0x00, 0x00, 0x01, 0xaa]) {
167            return Err(SpiError::BadResponse(interface.r1));
168        }
169
170        let host_capacity = if version_2 { 0x4000_0000 } else { 0 };
171        let mut ready = false;
172        for _ in 0..100 {
173            let app = self.command(55, 0, Reply::R1).await?;
174            if app.r1 > 0x01 {
175                return Err(SpiError::BadResponse(app.r1));
176            }
177            if self.command(41, host_capacity, Reply::R1).await?.r1 == 0x00 {
178                ready = true;
179                break;
180            }
181            self.delay.delay_ms(10).await;
182        }
183        if !ready {
184            return Err(SpiError::Timeout);
185        }
186
187        let ocr = self.command(58, 0, Reply::R1WithFourBytes).await?;
188        if ocr.r1 != 0x00 {
189            return Err(SpiError::BadResponse(ocr.r1));
190        }
191        self.high_capacity = ocr.extra[0] & 0x40 != 0;
192
193        if !self.high_capacity {
194            let length = self.command(16, BLOCK_SIZE as u32, Reply::R1).await?;
195            if length.r1 != 0x00 {
196                return Err(SpiError::BadResponse(length.r1));
197            }
198        }
199
200        self.check_crc = self.command(59, 1, Reply::R1).await?.r1 == 0x00;
201
202        let csd = self.read_csd().await?;
203        self.blocks = blocks_from_csd(&csd).ok_or(SpiError::UnsupportedCard)?;
204        Ok(())
205    }
206
207    /// The SPI device, when the card is no longer wanted.
208    pub fn into_spi(self) -> SPI {
209        self.spi
210    }
211
212    /// The card's size in 512-byte blocks.
213    pub fn blocks(&self) -> u32 {
214        self.blocks
215    }
216
217    /// Whether the card is SDHC or SDXC (block addressed) rather than standard capacity.
218    pub fn is_high_capacity(&self) -> bool {
219        self.high_capacity
220    }
221
222    /// The device, for raising its clock once the card is initialised.
223    pub fn spi_mut(&mut self) -> &mut SPI {
224        &mut self.spi
225    }
226
227    async fn read_block_inner(
228        &mut self,
229        block: u32,
230        buffer: &mut [u8; BLOCK_SIZE],
231    ) -> Result<(), SpiError<SPI::Error>> {
232        let address = if self.high_capacity {
233            block
234        } else {
235            block
236                .checked_mul(BLOCK_SIZE as u32)
237                .ok_or(SpiError::OutOfRange)?
238        };
239        self.read_with_data(17, address, buffer).await
240    }
241
242    /// Writes one block with CMD24. Chip select stays low from the command through the card's data response, so the
243    /// card never sees it rise between the command and the block; the card's programming time is waited out
244    /// afterwards, polling with chip select released between polls.
245    #[cfg(feature = "write")]
246    async fn write_block_inner(
247        &mut self,
248        block: u32,
249        buffer: &[u8; BLOCK_SIZE],
250    ) -> Result<(), SpiError<SPI::Error>> {
251        if block >= self.blocks {
252            return Err(SpiError::OutOfRange);
253        }
254        let address = if self.high_capacity {
255            block
256        } else {
257            block
258                .checked_mul(BLOCK_SIZE as u32)
259                .ok_or(SpiError::OutOfRange)?
260        };
261        let mut result = self.write_block_once(address, buffer).await;
262        for _ in 0..WRITE_RETRIES {
263            if !matches!(result, Err(SpiError::BadCrc)) {
264                break;
265            }
266            result = self.write_block_once(address, buffer).await;
267        }
268        result
269    }
270
271    #[cfg(feature = "write")]
272    async fn write_block_once(
273        &mut self,
274        address: u32,
275        buffer: &[u8; BLOCK_SIZE],
276    ) -> Result<(), SpiError<SPI::Error>> {
277        // Like every command after a read, this one needs the line idle first: on hardware (2026-11-28, an SDHC card on an
278        // RP2350) the first byte after a read was not 0xff, and a command sent over it saw 0xc2 as its R1. Clock until the
279        // card is idle (this also waits out a previous write's programming).
280        self.wait_not_busy().await?;
281        let frame = command_frame(24, address);
282        let crc = crc16(buffer).to_be_bytes();
283        // The card answers with an R1 within eight bytes and takes the data token any time after it, so the token goes
284        // after a fixed window of idle bytes. If the R1 is not zero the card ignores the block and the error is
285        // reported below.
286        let mut r1_window = [0xffu8; R1_WINDOW];
287        let mut response = [0xffu8; 1];
288        self.spi
289            .transaction(&mut [
290                Operation::Write(&frame),
291                Operation::TransferInPlace(&mut r1_window),
292                Operation::Write(&[0xfe]),
293                Operation::Write(buffer),
294                Operation::Write(&crc),
295                Operation::TransferInPlace(&mut response),
296            ])
297            .await
298            .map_err(SpiError::Spi)?;
299
300        let r1 = r1_window
301            .iter()
302            .copied()
303            .find(|byte| *byte != 0xff)
304            .ok_or(SpiError::Timeout)?;
305        if r1 != 0x00 {
306            return Err(SpiError::BadResponse(r1));
307        }
308        // The card answers the block with a data response in the byte after the CRC. Idle there means it sent none.
309        if response[0] == 0xff {
310            return Err(SpiError::Timeout);
311        }
312        // The data response is `xxx0sss1`; `sss` is 010 accepted, 101 CRC error, 110 write error.
313        let status = match response[0] & 0x1f {
314            0x05 => Ok(()),
315            0x0b => Err(SpiError::BadCrc),
316            other => Err(SpiError::WriteRejected(other)),
317        };
318        // A card can hold the line low after a rejected block too, and would take the next command's bytes as part of
319        // that: wait it out either way.
320        self.wait_not_busy().await?;
321        status
322    }
323
324    /// Waits for the card to finish programming: it holds the line low until it is done.
325    #[cfg(feature = "write")]
326    async fn wait_not_busy(&mut self) -> Result<(), SpiError<SPI::Error>> {
327        for poll in 0..WRITE_FAST_POLLS + WRITE_SLOW_POLLS {
328            let mut byte = [0xffu8];
329            self.spi
330                .transaction(&mut [Operation::TransferInPlace(&mut byte)])
331                .await
332                .map_err(SpiError::Spi)?;
333            if byte[0] == 0xff {
334                return Ok(());
335            }
336            if poll < WRITE_FAST_POLLS {
337                self.delay.delay_us(READ_TOKEN_POLL_US).await;
338            } else {
339                self.delay.delay_ms(1).await;
340            }
341        }
342        Err(SpiError::Timeout)
343    }
344
345    async fn read_csd(&mut self) -> Result<[u8; 16], SpiError<SPI::Error>> {
346        let mut csd = [0u8; 16];
347        self.read_with_data(9, 0, &mut csd).await?;
348        Ok(csd)
349    }
350
351    /// A command that answers with a data block. A read whose token came later than the window allowed can fail on a
352    /// card that cannot resume a block after chip select rises (hardware, 2026-11-25: about 1 % of scattered reads on
353    /// an SDHC card, the same blocks at every clock). That failure widened the window, so the repeat is one
354    /// transaction; the caller never sees the first failure.
355    async fn read_with_data(
356        &mut self,
357        index: u8,
358        argument: u32,
359        buffer: &mut [u8],
360    ) -> Result<(), SpiError<SPI::Error>> {
361        let mut result = self.read_with_data_once(index, argument, buffer).await;
362        for _ in 0..READ_RETRIES {
363            if !matches!(
364                result,
365                Err(SpiError::BadResponse(_) | SpiError::Timeout | SpiError::BadCrc)
366            ) {
367                break;
368            }
369            result = self.read_with_data_once(index, argument, buffer).await;
370        }
371        result
372    }
373
374    /// One attempt: one chip-select assertion when the token arrives inside the window and polling otherwise.
375    async fn read_with_data_once(
376        &mut self,
377        index: u8,
378        argument: u32,
379        buffer: &mut [u8],
380    ) -> Result<(), SpiError<SPI::Error>> {
381        let frame = command_frame(index, argument);
382        let window = self.token_window;
383        let length = R1_WINDOW + window + 1 + buffer.len() + 2;
384        let scratch = &mut self.scratch[..length];
385        scratch.fill(0xff);
386        self.spi
387            .transaction(&mut [
388                Operation::Write(&frame),
389                Operation::TransferInPlace(scratch),
390            ])
391            .await
392            .map_err(SpiError::Spi)?;
393
394        let r1_at = scratch[..R1_WINDOW]
395            .iter()
396            .position(|byte| *byte != 0xff)
397            .ok_or(SpiError::Timeout)?;
398        let r1 = scratch[r1_at];
399        if r1 != 0x00 {
400            return Err(SpiError::BadResponse(r1));
401        }
402
403        // The token can be anywhere after the R1, including past the window: the transaction clocks
404        // idle bytes through the block's own part of the buffer too, so search all of it.
405        let first_idle = r1_at + 1;
406        let wanted = buffer.len() + 2;
407        let mut crc = [0xffu8; 2];
408        if let Some(gap) = scratch[first_idle..].iter().position(|byte| *byte != 0xff) {
409            let token_at = first_idle + gap;
410            let token = scratch[token_at];
411            let after = &scratch[token_at + 1..];
412            let have = after.len().min(wanted);
413            let data_have = have.min(buffer.len());
414            if token == 0xfe {
415                buffer[..data_have].copy_from_slice(&after[..data_have]);
416                crc[..have - data_have].copy_from_slice(&after[data_have..have]);
417            }
418            self.learn_gap(gap);
419            if token != 0xfe {
420                return Err(SpiError::BadResponse(token));
421            }
422            return if have == wanted {
423                self.check_data(buffer, u16::from_be_bytes(crc))
424            } else {
425                self.finish_block(buffer, data_have, crc, have - data_have)
426                    .await
427            };
428        }
429
430        let mut waited = length - first_idle;
431        self.token_window = MAX_TOKEN_WINDOW;
432        let mut token = 0xff;
433        for _ in 0..READ_TOKEN_POLLS {
434            let mut byte = [0xff];
435            self.spi
436                .transaction(&mut [Operation::TransferInPlace(&mut byte)])
437                .await
438                .map_err(SpiError::Spi)?;
439            token = byte[0];
440            if token != 0xff {
441                break;
442            }
443            waited += 1;
444            self.delay.delay_us(READ_TOKEN_POLL_US).await;
445        }
446        if token != 0xfe {
447            return Err(SpiError::BadResponse(token));
448        }
449        self.learn_gap(waited);
450        self.finish_block(buffer, 0, crc, 0).await
451    }
452
453    /// Reads the rest of a block whose first `data_have` data bytes and `crc_have` CRC bytes are in hand.
454    async fn finish_block(
455        &mut self,
456        buffer: &mut [u8],
457        data_have: usize,
458        mut crc: [u8; 2],
459        crc_have: usize,
460    ) -> Result<(), SpiError<SPI::Error>> {
461        buffer[data_have..].fill(0xff);
462        self.spi
463            .transaction(&mut [
464                Operation::TransferInPlace(&mut buffer[data_have..]),
465                Operation::TransferInPlace(&mut crc[crc_have..]),
466            ])
467            .await
468            .map_err(SpiError::Spi)?;
469        self.check_data(buffer, u16::from_be_bytes(crc))
470    }
471
472    fn learn_gap(&mut self, gap: usize) {
473        self.token_window = (gap * 2 + MIN_TOKEN_WINDOW).clamp(MIN_TOKEN_WINDOW, MAX_TOKEN_WINDOW);
474    }
475
476    fn check_data(&self, buffer: &[u8], received: u16) -> Result<(), SpiError<SPI::Error>> {
477        if self.check_crc && crc16(buffer) != received {
478            return Err(SpiError::BadCrc);
479        }
480        Ok(())
481    }
482
483    /// One chip-select assertion covers the command frame and its response whenever the response
484    /// length is known, so the card never sees chip select drop between them.
485    async fn command(
486        &mut self,
487        index: u8,
488        argument: u32,
489        reply: Reply,
490    ) -> Result<Response, SpiError<SPI::Error>> {
491        let frame = command_frame(index, argument);
492
493        let mut bytes = [0xffu8; 12];
494        self.spi
495            .transaction(&mut [
496                Operation::Write(&frame),
497                Operation::TransferInPlace(&mut bytes),
498            ])
499            .await
500            .map_err(SpiError::Spi)?;
501        let position = bytes[..8]
502            .iter()
503            .position(|byte| *byte != 0xff)
504            .ok_or(SpiError::Timeout)?;
505        let mut extra = [0u8; 4];
506        if let Reply::R1WithFourBytes = reply {
507            extra.copy_from_slice(&bytes[position + 1..position + 5]);
508        }
509        Ok(Response {
510            r1: bytes[position],
511            extra,
512        })
513    }
514}
515
516impl<SPI, D> BlockDevice for SpiSdCard<SPI, D>
517where
518    SPI: SpiDevice<u8>,
519    D: DelayNs,
520{
521    type Error = SpiError<SPI::Error>;
522
523    async fn read_block(
524        &mut self,
525        block: u32,
526        buffer: &mut [u8; BLOCK_SIZE],
527    ) -> Result<(), Self::Error> {
528        self.read_block_inner(block, buffer).await
529    }
530
531    async fn num_blocks(&mut self) -> Result<u32, Self::Error> {
532        Ok(self.blocks)
533    }
534}
535
536#[cfg(feature = "write")]
537impl<SPI, D> crate::BlockWrite for SpiSdCard<SPI, D>
538where
539    SPI: SpiDevice<u8>,
540    D: DelayNs,
541{
542    async fn write_block(
543        &mut self,
544        block: u32,
545        buffer: &[u8; BLOCK_SIZE],
546    ) -> Result<(), Self::Error> {
547        self.write_block_inner(block, buffer).await
548    }
549}
550
551fn command_frame(index: u8, argument: u32) -> [u8; 6] {
552    let mut frame = [
553        0x40 | index,
554        (argument >> 24) as u8,
555        (argument >> 16) as u8,
556        (argument >> 8) as u8,
557        argument as u8,
558        0,
559    ];
560    frame[5] = crc7(&frame[..5]);
561    frame
562}
563
564fn blocks_from_csd(csd: &[u8; 16]) -> Option<u32> {
565    let structure = csd[0] >> 6;
566    let blocks = match structure {
567        0 => {
568            let read_bl_len = u32::from(csd[5] & 0x0f);
569            let c_size = (u64::from(csd[6] & 0x03) << 10)
570                | (u64::from(csd[7]) << 2)
571                | (u64::from(csd[8]) >> 6);
572            let c_size_mult = (u32::from(csd[9] & 0x03) << 1) | (u32::from(csd[10]) >> 7);
573            ((c_size + 1) << (c_size_mult + 2 + read_bl_len)) / BLOCK_SIZE as u64
574        }
575        1 => {
576            let c_size =
577                (u64::from(csd[7] & 0x3f) << 16) | (u64::from(csd[8]) << 8) | u64::from(csd[9]);
578            (c_size + 1) * 1024
579        }
580        _ => return None,
581    };
582    Some(u32::try_from(blocks).unwrap_or(u32::MAX).max(1))
583}
584
585/// CRC7 with the SD polynomial x^7 + x^3 + 1, returned as the command frame's
586/// CRC byte (shifted left and with the end bit set).
587pub fn crc7(data: &[u8]) -> u8 {
588    let mut crc = 0u8;
589    for &byte in data {
590        for bit in (0..8).rev() {
591            crc <<= 1;
592            if ((byte >> bit) & 1) ^ ((crc >> 7) & 1) != 0 {
593                crc ^= 0x09;
594            }
595        }
596    }
597    ((crc & 0x7f) << 1) | 1
598}
599
600/// CRC16 with the SD data polynomial x^16 + x^12 + x^5 + 1.
601pub fn crc16(data: &[u8]) -> u16 {
602    let mut crc = 0u16;
603    for &byte in data {
604        crc ^= u16::from(byte) << 8;
605        for _ in 0..8 {
606            crc = if crc & 0x8000 != 0 {
607                (crc << 1) ^ 0x1021
608            } else {
609                crc << 1
610            };
611        }
612    }
613    crc
614}
615
616#[cfg(test)]
617mod tests {
618    use super::{blocks_from_csd, crc16, crc7};
619
620    #[test]
621    fn a_version_1_csd_with_the_largest_fields_does_not_overflow() {
622        let mut csd = [0u8; 16];
623        csd[5] = 0x0b;
624        csd[6] = 0x03;
625        csd[7] = 0xff;
626        csd[8] = 0xc0;
627        csd[9] = 0x03;
628        csd[10] = 0x80;
629        assert_eq!(blocks_from_csd(&csd), Some(1 << 23));
630    }
631
632    #[test]
633    fn a_version_2_csd_at_the_maximum_c_size_saturates_instead_of_overflowing() {
634        let mut csd = [0u8; 16];
635        csd[0] = 0x40;
636        csd[7] = 0x3f;
637        csd[8] = 0xff;
638        csd[9] = 0xff;
639        assert_eq!(blocks_from_csd(&csd), Some(u32::MAX));
640    }
641
642    #[test]
643    fn an_unknown_csd_structure_is_unsupported() {
644        let mut csd = [0u8; 16];
645        csd[0] = 0x80;
646        assert_eq!(blocks_from_csd(&csd), None);
647    }
648
649    #[test]
650    fn crc7_matches_the_sd_command_frames() {
651        assert_eq!(crc7(&[0x40, 0x00, 0x00, 0x00, 0x00]), 0x95);
652        assert_eq!(crc7(&[0x48, 0x00, 0x00, 0x01, 0xaa]), 0x87);
653    }
654
655    #[test]
656    fn crc16_matches_the_sd_data_reference() {
657        // CRC-16/XMODEM (initial value 0), the SD data CRC.
658        assert_eq!(crc16(b"123456789"), 0x31c3);
659    }
660}