mpfs-hal 0.4.1

Hardware Abstraction Layer for PolarFire SoC
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
use crate::{Mutex, pac};
use embassy_embedded_hal::SetConfig;
use embedded_hal::spi::{ErrorType, Operation, Phase, Polarity};
use paste::paste;

// Master mode only
// TODO: Add slave mode

pub fn init() {
    unsafe {
        pac::mss_config_clk_rst(
            pac::mss_peripherals__MSS_PERIPH_SPI0,
            pac::MPFS_HAL_FIRST_HART as u8,
            pac::PERIPH_RESET_STATE__PERIPHERAL_ON,
        );
        pac::mss_config_clk_rst(
            pac::mss_peripherals__MSS_PERIPH_SPI1,
            pac::MPFS_HAL_FIRST_HART as u8,
            pac::PERIPH_RESET_STATE__PERIPHERAL_ON,
        );
        pac::MSS_SPI_init(&raw mut pac::g_mss_spi0_lo);
        pac::MSS_SPI_init(&raw mut pac::g_mss_spi1_lo);

        // Add for slave mode
        // pac::PLIC_SetPriority(pac::PLIC_IRQn_Type_PLIC_SPI0_INT_OFFSET, 2);
        // pac::PLIC_SetPriority(pac::PLIC_IRQn_Type_PLIC_SPI1_INT_OFFSET, 2);
        // pac::PLIC_EnableIRQ(pac::PLIC_IRQn_Type_PLIC_SPI0_INT_OFFSET);
        // pac::PLIC_EnableIRQ(pac::PLIC_IRQn_Type_PLIC_SPI1_INT_OFFSET);
    }
    debug!("SPI initialized");
}

pub trait SpiPeripheral: crate::Peripheral {
    #[doc(hidden)]
    fn address(&self) -> *mut pac::mss_spi_instance_t;
    #[doc(hidden)]
    fn number(&self) -> u8;
    #[doc(hidden)]
    fn slave_num(&self) -> u8;
}

#[derive(Debug)]
pub enum SpiError {
    InvalidClockDiv,
}

impl embedded_hal::spi::Error for SpiError {
    fn kind(&self) -> embedded_hal::spi::ErrorKind {
        embedded_hal::spi::ErrorKind::Other
    }
}

static SPI0_IN_USE: Mutex = Mutex::new();
static SPI1_IN_USE: Mutex = Mutex::new();

macro_rules! impl_spi {
    ($n:expr, $slave_num:expr) => {
        paste! {
            impl_spi!([<Spi $n Slave $slave_num>], [<SPI $n _SLAVE $slave_num _TAKEN>], $n, $slave_num, [<g_mss_spi $n _lo>]);
        }
    };

    // E.g. impl_uart!(SPI0_SLAVE0, SPI0_SLAVE0_TAKEN, 0, 0, g_mss_spi_0_lo);
    ($PERIPH:ident, $PERIPH_TAKEN:ident, $spi_num:expr, $slave_num:expr, $instance:ident) => {
        pub struct $PERIPH {
            _private: (),
        }
        static mut $PERIPH_TAKEN: bool = false;

        impl crate::Peripheral for $PERIPH {
            fn take() -> Option<Self> {
                critical_section::with(|_| unsafe {
                    if $PERIPH_TAKEN {
                        None
                    } else {
                        $PERIPH_TAKEN = true;
                        Some(Self { _private: () })
                    }
                })
            }

            unsafe fn steal() -> Self {
                Self { _private: () }
            }
        }
        impl SpiPeripheral for $PERIPH {
            fn address(&self) -> *mut pac::mss_spi_instance_t {
                &raw mut pac::$instance
            }

            fn number(&self) -> u8 {
                $spi_num
            }

            fn slave_num(&self) -> u8 {
                $slave_num
            }
        }

    };
}

impl_spi!(0, 0);
impl_spi!(0, 1);
impl_spi!(1, 0);
impl_spi!(1, 1);

#[derive(Debug, Clone, Copy)]
pub struct SpiConfig {
    /// Clock divider, must be even between 2 to 512.
    /// The base clock is 150MHz, so the actual clock will be 150MHz / clock_div.
    /// Any value less than 8 results in instability on the CS line.
    clock_div: u16,
    phase: Phase,
    polarity: Polarity,
}

impl Default for SpiConfig {
    fn default() -> Self {
        Self {
            clock_div: 8,
            phase: Phase::CaptureOnFirstTransition,
            polarity: Polarity::IdleLow,
        }
    }
}

impl SpiConfig {
    pub fn new(clock_div: u16, phase: Phase, polarity: Polarity) -> Result<Self, SpiError> {
        if clock_div < 2 || clock_div > 512 || clock_div % 2 != 0 {
            return Err(SpiError::InvalidClockDiv);
        }
        Ok(Self {
            clock_div,
            phase,
            polarity,
        })
    }
}

pub struct Spi<T: SpiPeripheral> {
    peripheral: T,
}

impl<T: SpiPeripheral> ErrorType for Spi<T> {
    type Error = SpiError;
}

impl<T: SpiPeripheral> Spi<T> {
    pub fn new(peripheral: T, config: SpiConfig) -> Self {
        let mut spi = Spi { peripheral };
        spi.set_config(&config).unwrap();
        spi
    }
}

impl<T: SpiPeripheral> SetConfig for Spi<T> {
    type Config = SpiConfig;
    type ConfigError = SpiError;
    fn set_config(&mut self, config: &Self::Config) -> Result<(), Self::ConfigError> {
        let mode = match (config.phase, config.polarity) {
            (Phase::CaptureOnFirstTransition, Polarity::IdleLow) => {
                pac::__mss_spi_protocol_mode_t_MSS_SPI_MODE0
            }
            (Phase::CaptureOnSecondTransition, Polarity::IdleLow) => {
                pac::__mss_spi_protocol_mode_t_MSS_SPI_MODE1
            }
            (Phase::CaptureOnFirstTransition, Polarity::IdleHigh) => {
                pac::__mss_spi_protocol_mode_t_MSS_SPI_MODE2
            }
            (Phase::CaptureOnSecondTransition, Polarity::IdleHigh) => {
                pac::__mss_spi_protocol_mode_t_MSS_SPI_MODE3
            }
        };
        unsafe {
            pac::MSS_SPI_configure_master_mode(
                self.peripheral.address(),
                self.peripheral.slave_num() as u32,
                mode,
                config.clock_div as u32,
                pac::MSS_SPI_BLOCK_TRANSFER_FRAME_SIZE as u8, // This is ignored
                Some(mss_spi_overflow_handler),
            );
        }
        Ok(())
    }
}

extern "C" fn mss_spi_overflow_handler(mss_spi_core: u8) {
    unsafe {
        if mss_spi_core != 0 {
            // reset SPI1
            pac::mss_config_clk_rst(
                pac::mss_peripherals__MSS_PERIPH_SPI1,
                pac::MPFS_HAL_FIRST_HART as u8,
                pac::PERIPH_RESET_STATE__PERIPHERAL_OFF,
            );
            // Take SPI1 out of reset
            pac::mss_config_clk_rst(
                pac::mss_peripherals__MSS_PERIPH_SPI1,
                pac::MPFS_HAL_FIRST_HART as u8,
                pac::PERIPH_RESET_STATE__PERIPHERAL_ON,
            );
        } else {
            // reset SPI0
            pac::mss_config_clk_rst(
                pac::mss_peripherals__MSS_PERIPH_SPI0,
                pac::MPFS_HAL_FIRST_HART as u8,
                pac::PERIPH_RESET_STATE__PERIPHERAL_OFF,
            );
            // Take SPI0 out of reset
            pac::mss_config_clk_rst(
                pac::mss_peripherals__MSS_PERIPH_SPI0,
                pac::MPFS_HAL_FIRST_HART as u8,
                pac::PERIPH_RESET_STATE__PERIPHERAL_ON,
            );
        }
    }
}

impl<T: SpiPeripheral> embedded_hal::spi::SpiDevice for Spi<T> {
    fn transaction(&mut self, operations: &mut [Operation<'_, u8>]) -> Result<(), Self::Error> {
        let mutex = if self.peripheral.number() == 0 {
            &SPI0_IN_USE
        } else {
            &SPI1_IN_USE
        };
        let lock = mutex.lock();

        unsafe {
            pac::MSS_SPI_set_slave_select(
                self.peripheral.address(),
                self.peripheral.slave_num() as u32,
            );
            for operation in operations {
                match operation {
                    Operation::Write(data) => {
                        self.write(data)?;
                    }
                    Operation::Read(data) => {
                        self.read(data)?;
                    }
                    Operation::Transfer(rx, tx) => {
                        self.transfer(rx, tx)?;
                    }
                    Operation::TransferInPlace(data) => {
                        self.transfer_in_place(data)?;
                    }
                    Operation::DelayNs(ns) => {
                        pac::sleep_ms(*ns as u64 / 1000);
                    }
                }
            }
            pac::MSS_SPI_clear_slave_select(
                self.peripheral.address(),
                self.peripheral.slave_num() as u32,
            );
        }
        mutex.release(lock);

        Ok(())
    }
}

impl<T: SpiPeripheral> Spi<T> {
    fn write(&mut self, data: &[u8]) -> Result<(), SpiError> {
        if data.is_empty() {
            return Ok(());
        }
        let buffer_aligned: bool = data.as_ptr().align_offset(4) == 0 && data.len() > 3;
        trace!(
            "Writing to SPI {:x?}. Buffer aligned: {}; Byte count: {}",
            data,
            buffer_aligned,
            data.len()
        );

        unsafe {
            let spi = &mut (*(*self.peripheral.address()).hw_reg);

            let word_count = if buffer_aligned { data.len() / 4 } else { 0 } as u32;
            if word_count > 0 {
                // Transfer 32-bit aligned words
                let words = data.as_ptr() as *const u32;

                // Setup registers - single volatile write for initial setup
                spi.FRAMESIZE = 32;
                spi.FRAMESUP = word_count as u32 & pac::spi::BYTESUPPER_MASK;
                let control = (spi.CONTROL & !pac::spi::TXRXDFCOUNT_MASK)
                    | ((word_count << pac::spi::TXRXDFCOUNT_SHIFT) & pac::spi::TXRXDFCOUNT_MASK);
                spi.CONTROL = control | pac::spi::CTRL_ENABLE_MASK;
                core::sync::atomic::fence(core::sync::atomic::Ordering::SeqCst);

                // Flush the receive FIFO - needs volatile read
                while (core::ptr::read_volatile(&spi.STATUS) & pac::spi::RX_FIFO_EMPTY_MASK) == 0 {
                    let _ = core::ptr::read_volatile(&spi.RX_DATA);
                }

                for i in 0..(word_count as usize) {
                    // Wait until transmit FIFO is not full - needs volatile read
                    while (core::ptr::read_volatile(&spi.STATUS) & pac::spi::TX_FIFO_FULL_MASK) != 0
                    {
                        core::hint::spin_loop();
                    }
                    // TX_DATA write needs to be volatile
                    core::ptr::write_volatile(&mut spi.TX_DATA, (*words.add(i)).to_be());
                }

                // Wait until the transfer is done - needs volatile read
                while (core::ptr::read_volatile(&spi.STATUS) & pac::spi::ACTIVE_MASK) != 0 {
                    core::hint::spin_loop();
                }

                // Reset state - single write is fine
                spi.COMMAND |= pac::spi::TX_FIFO_RESET_MASK | pac::spi::RX_FIFO_RESET_MASK;
                spi.CONTROL &= !pac::spi::CTRL_ENABLE_MASK;
                core::sync::atomic::fence(core::sync::atomic::Ordering::SeqCst);
            }

            let data = &data[word_count as usize * 4..];

            if !data.is_empty() {
                // Setup registers - single volatile write for initial setup
                spi.FRAMESIZE = 8;
                spi.FRAMESUP = data.len() as u32 & pac::spi::BYTESUPPER_MASK;
                let control = (spi.CONTROL & !pac::spi::TXRXDFCOUNT_MASK)
                    | (((data.len() as u32) << pac::spi::TXRXDFCOUNT_SHIFT)
                        & pac::spi::TXRXDFCOUNT_MASK);
                spi.CONTROL = control | pac::spi::CTRL_ENABLE_MASK;
                core::sync::atomic::fence(core::sync::atomic::Ordering::SeqCst);

                // Flush the receive FIFO - needs volatile read
                while (core::ptr::read_volatile(&spi.STATUS) & pac::spi::RX_FIFO_EMPTY_MASK) == 0 {
                    let _ = core::ptr::read_volatile(&spi.RX_DATA);
                }

                for i in 0..data.len() {
                    // Wait until transmit FIFO is not full - needs volatile read
                    while (core::ptr::read_volatile(&spi.STATUS) & pac::spi::TX_FIFO_FULL_MASK) != 0
                    {
                        core::hint::spin_loop();
                    }
                    // TX_DATA write needs to be volatile
                    core::ptr::write_volatile(&mut spi.TX_DATA, data[i] as u32);
                }

                // Wait until the transfer is done - needs volatile read
                while (core::ptr::read_volatile(&spi.STATUS) & pac::spi::ACTIVE_MASK) != 0 {
                    core::hint::spin_loop();
                }

                // Reset state - single write is fine
                spi.COMMAND |= pac::spi::TX_FIFO_RESET_MASK | pac::spi::RX_FIFO_RESET_MASK;
                spi.CONTROL &= !pac::spi::CTRL_ENABLE_MASK;
                core::sync::atomic::fence(core::sync::atomic::Ordering::SeqCst);
            }
        }
        Ok(())
    }

    fn read(&mut self, data: &mut [u8]) -> Result<(), SpiError> {
        if data.is_empty() {
            return Ok(());
        }
        let buffer_aligned: bool = data.as_ptr().align_offset(4) == 0 && data.len() > 3;

        trace!(
            "Reading from SPI. Buffer aligned: {}; Byte count: {}",
            buffer_aligned,
            data.len()
        );

        unsafe {
            let spi = &mut (*(*self.peripheral.address()).hw_reg);
            let word_count = if buffer_aligned { data.len() / 4 } else { 0 } as u32;
            if word_count > 0 {
                let words = data.as_ptr() as *mut u32;

                // Setup registers - single volatile write for initial setup
                spi.FRAMESIZE = 32;
                spi.FRAMESUP = word_count as u32 & pac::spi::BYTESUPPER_MASK;
                let control = (spi.CONTROL & !pac::spi::TXRXDFCOUNT_MASK)
                    | ((word_count << pac::spi::TXRXDFCOUNT_SHIFT) & pac::spi::TXRXDFCOUNT_MASK);
                spi.CONTROL = control | pac::spi::CTRL_ENABLE_MASK;
                core::sync::atomic::fence(core::sync::atomic::Ordering::SeqCst);

                // Flush the receive FIFO - needs volatile read
                while (core::ptr::read_volatile(&spi.STATUS) & pac::spi::RX_FIFO_EMPTY_MASK) == 0 {
                    let _ = core::ptr::read_volatile(&spi.RX_DATA);
                }

                for i in 0..(word_count as usize) {
                    // Wait until transmit FIFO is not full - needs volatile read
                    while (core::ptr::read_volatile(&spi.STATUS) & pac::spi::TX_FIFO_FULL_MASK) != 0
                    {
                        core::hint::spin_loop();
                    }
                    // TX_DATA write needs to be volatile
                    core::ptr::write_volatile(&mut spi.TX_DATA, 0xFFFFFFFF);
                    // Status and RX_DATA reads need to be volatile
                    while (core::ptr::read_volatile(&spi.STATUS) & pac::spi::RX_FIFO_EMPTY_MASK)
                        != 0
                    {
                        core::hint::spin_loop();
                    }
                    *words.add(i) = core::ptr::read_volatile(&spi.RX_DATA).to_be();
                }

                // Wait until the transfer is done - needs volatile read
                while (core::ptr::read_volatile(&spi.STATUS) & pac::spi::ACTIVE_MASK) != 0 {
                    core::hint::spin_loop();
                }

                // Reset state - single write is fine
                spi.COMMAND |= pac::spi::TX_FIFO_RESET_MASK | pac::spi::RX_FIFO_RESET_MASK;
                spi.CONTROL &= !pac::spi::CTRL_ENABLE_MASK;
                core::sync::atomic::fence(core::sync::atomic::Ordering::SeqCst);
            }

            let data = &mut data[word_count as usize * 4..];

            if !data.is_empty() {
                // Setup registers - single volatile write for initial setup
                spi.FRAMESIZE = 8;
                spi.FRAMESUP = data.len() as u32 & pac::spi::BYTESUPPER_MASK;
                let control = (spi.CONTROL & !pac::spi::TXRXDFCOUNT_MASK)
                    | (((data.len() as u32) << pac::spi::TXRXDFCOUNT_SHIFT)
                        & pac::spi::TXRXDFCOUNT_MASK);
                spi.CONTROL = control | pac::spi::CTRL_ENABLE_MASK;
                core::sync::atomic::fence(core::sync::atomic::Ordering::SeqCst);

                // Flush the receive FIFO - needs volatile read
                while (core::ptr::read_volatile(&spi.STATUS) & pac::spi::RX_FIFO_EMPTY_MASK) == 0 {
                    let _ = core::ptr::read_volatile(&spi.RX_DATA);
                }

                for i in 0..data.len() {
                    // Wait until transmit FIFO is not full - needs volatile read
                    while (core::ptr::read_volatile(&spi.STATUS) & pac::spi::TX_FIFO_FULL_MASK) != 0
                    {
                        core::hint::spin_loop();
                    }
                    // TX_DATA write needs to be volatile
                    core::ptr::write_volatile(&mut spi.TX_DATA, 0xFFFFFFFF);
                    // Status and RX_DATA reads need to be volatile
                    while (core::ptr::read_volatile(&spi.STATUS) & pac::spi::RX_FIFO_EMPTY_MASK)
                        != 0
                    {
                        core::hint::spin_loop();
                    }
                    data[i] = core::ptr::read_volatile(&spi.RX_DATA) as u8;
                }

                // Wait until the transfer is done - needs volatile read
                while (core::ptr::read_volatile(&spi.STATUS) & pac::spi::ACTIVE_MASK) != 0 {
                    core::hint::spin_loop();
                }

                // Reset state - single write is fine
                spi.COMMAND |= pac::spi::TX_FIFO_RESET_MASK | pac::spi::RX_FIFO_RESET_MASK;
                spi.CONTROL &= !pac::spi::CTRL_ENABLE_MASK;
                core::sync::atomic::fence(core::sync::atomic::Ordering::SeqCst);
            }
        }

        Ok(())
    }

    fn transfer(&mut self, read: &mut [u8], write: &[u8]) -> Result<(), SpiError> {
        if read.is_empty() && write.is_empty() {
            return Ok(());
        }
        let buffer_aligned: bool = write.as_ptr().align_offset(4) == 0
            && read.as_ptr().align_offset(4) == 0
            && (write.len() > 3 || read.len() > 3);

        trace!(
            "Transferring from SPI. Read len: {}; Write: {:x?}; Buffer aligned: {}",
            read.len(),
            write,
            buffer_aligned
        );

        let total_bytes = read.len().max(write.len());
        let mut tx_bytes_sent = 0;
        let mut rx_bytes_received = 0;

        unsafe {
            let spi = &mut (*(*self.peripheral.address()).hw_reg);
            let word_count = if buffer_aligned { total_bytes / 4 } else { 0 } as u32;
            if word_count > 0 {
                let tx_words = write.as_ptr() as *mut u32;
                let rx_words = read.as_ptr() as *mut u32;

                // Setup registers - single volatile write for initial setup
                spi.FRAMESIZE = 32;
                spi.FRAMESUP = word_count as u32 & pac::spi::BYTESUPPER_MASK;
                let control = (spi.CONTROL & !pac::spi::TXRXDFCOUNT_MASK)
                    | ((word_count << pac::spi::TXRXDFCOUNT_SHIFT) & pac::spi::TXRXDFCOUNT_MASK);
                spi.CONTROL = control | pac::spi::CTRL_ENABLE_MASK;
                core::sync::atomic::fence(core::sync::atomic::Ordering::SeqCst);

                // Flush the receive FIFO - needs volatile read
                while (core::ptr::read_volatile(&spi.STATUS) & pac::spi::RX_FIFO_EMPTY_MASK) == 0 {
                    let _ = core::ptr::read_volatile(&spi.RX_DATA);
                }

                for i in 0..(word_count as usize) {
                    // Wait until transmit FIFO is not full - needs volatile read
                    while (core::ptr::read_volatile(&spi.STATUS) & pac::spi::TX_FIFO_FULL_MASK) != 0
                    {
                        core::hint::spin_loop();
                    }
                    if tx_bytes_sent + 4 <= write.len() {
                        // TX_DATA write needs to be volatile
                        core::ptr::write_volatile(&mut spi.TX_DATA, (*tx_words.add(i)).to_be());
                        tx_bytes_sent += 4;
                    } else if tx_bytes_sent < write.len() {
                        let mut tx_data = 0x0;
                        let tx_bytes_remaining = write.len() - tx_bytes_sent;
                        while tx_bytes_sent < write.len() {
                            tx_data <<= 8;
                            tx_data |= write[tx_bytes_sent] as u32;
                            tx_bytes_sent += 1;
                        }
                        for _ in 0..(4 - tx_bytes_remaining) {
                            tx_data <<= 8;
                            tx_data |= 0xFF;
                        }
                        // TX_DATA write needs to be volatile
                        core::ptr::write_volatile(&mut spi.TX_DATA, tx_data);
                    } else {
                        // TX_DATA write needs to be volatile
                        core::ptr::write_volatile(&mut spi.TX_DATA, 0xFFFFFFFF);
                    }
                    // Status and RX_DATA reads need to be volatile
                    while (core::ptr::read_volatile(&spi.STATUS) & pac::spi::RX_FIFO_EMPTY_MASK)
                        != 0
                    {
                        core::hint::spin_loop();
                    }
                    let word = core::ptr::read_volatile(&spi.RX_DATA);
                    if rx_bytes_received + 4 <= read.len() {
                        *rx_words.add(i) = word.to_be();
                        rx_bytes_received += 4;
                    } else if rx_bytes_received < read.len() {
                        let rx_bytes_remaining = read.len() - rx_bytes_received;
                        for i in 0..(4 - rx_bytes_remaining) {
                            read[rx_bytes_received] = (word >> (8 * i)) as u8;
                            rx_bytes_received += 1;
                        }
                    }
                }

                // Wait until the transfer is done - needs volatile read
                while (core::ptr::read_volatile(&spi.STATUS) & pac::spi::ACTIVE_MASK) != 0 {
                    core::hint::spin_loop();
                }

                // Reset state - single write is fine
                spi.COMMAND |= pac::spi::TX_FIFO_RESET_MASK | pac::spi::RX_FIFO_RESET_MASK;
                spi.CONTROL &= !pac::spi::CTRL_ENABLE_MASK;
                core::sync::atomic::fence(core::sync::atomic::Ordering::SeqCst);
            }

            let write = &write[tx_bytes_sent..];
            let read = &mut read[rx_bytes_received..];
            let remaining_bytes = read.len().max(write.len());

            if remaining_bytes > 0 {
                // Setup registers - single volatile write for initial setup
                spi.FRAMESIZE = 8;
                spi.FRAMESUP = remaining_bytes as u32 & pac::spi::BYTESUPPER_MASK;
                let control = (spi.CONTROL & !pac::spi::TXRXDFCOUNT_MASK)
                    | (((remaining_bytes as u32) << pac::spi::TXRXDFCOUNT_SHIFT)
                        & pac::spi::TXRXDFCOUNT_MASK);
                spi.CONTROL = control | pac::spi::CTRL_ENABLE_MASK;
                core::sync::atomic::fence(core::sync::atomic::Ordering::SeqCst);

                // Flush the receive FIFO - needs volatile read
                while (core::ptr::read_volatile(&spi.STATUS) & pac::spi::RX_FIFO_EMPTY_MASK) == 0 {
                    let _ = core::ptr::read_volatile(&spi.RX_DATA);
                }

                for i in 0..remaining_bytes {
                    // Wait until transmit FIFO is not full - needs volatile read
                    while (core::ptr::read_volatile(&spi.STATUS) & pac::spi::TX_FIFO_FULL_MASK) != 0
                    {
                        core::hint::spin_loop();
                    }
                    if i < write.len() {
                        // TX_DATA write needs to be volatile
                        core::ptr::write_volatile(&mut spi.TX_DATA, write[i] as u32);
                    }
                    // Status and RX_DATA reads need to be volatile
                    while (core::ptr::read_volatile(&spi.STATUS) & pac::spi::RX_FIFO_EMPTY_MASK)
                        != 0
                    {
                        core::hint::spin_loop();
                    }
                    if i < read.len() {
                        read[i] = core::ptr::read_volatile(&spi.RX_DATA) as u8;
                    }
                }

                // Wait until the transfer is done - needs volatile read
                while (core::ptr::read_volatile(&spi.STATUS) & pac::spi::ACTIVE_MASK) != 0 {
                    core::hint::spin_loop();
                }

                // Reset state - single write is fine
                spi.COMMAND |= pac::spi::TX_FIFO_RESET_MASK | pac::spi::RX_FIFO_RESET_MASK;
                spi.CONTROL &= !pac::spi::CTRL_ENABLE_MASK;
                core::sync::atomic::fence(core::sync::atomic::Ordering::SeqCst);
            }
        }

        Ok(())
    }

    fn transfer_in_place(&mut self, data: &mut [u8]) -> Result<(), SpiError> {
        if data.is_empty() {
            return Ok(());
        }

        let buffer_aligned: bool = data.as_ptr().align_offset(4) == 0 && data.len() > 3;
        trace!(
            "Transferring in place, buffer aligned? {}; Data: {:x?}",
            buffer_aligned,
            data
        );

        unsafe {
            let spi = &mut (*(*self.peripheral.address()).hw_reg);
            let word_count = if buffer_aligned { data.len() / 4 } else { 0 } as u32;

            if word_count > 0 {
                let words = data.as_ptr() as *mut u32;

                // Setup registers - single volatile write for initial setup
                spi.FRAMESIZE = 32;
                spi.FRAMESUP = word_count as u32 & pac::spi::BYTESUPPER_MASK;
                let control = (spi.CONTROL & !pac::spi::TXRXDFCOUNT_MASK)
                    | ((word_count << pac::spi::TXRXDFCOUNT_SHIFT) & pac::spi::TXRXDFCOUNT_MASK);
                spi.CONTROL = control | pac::spi::CTRL_ENABLE_MASK;
                core::sync::atomic::fence(core::sync::atomic::Ordering::SeqCst);

                // Flush the receive FIFO - needs volatile read
                while (core::ptr::read_volatile(&spi.STATUS) & pac::spi::RX_FIFO_EMPTY_MASK) == 0 {
                    let _ = core::ptr::read_volatile(&spi.RX_DATA);
                }

                for i in 0..(word_count as usize) {
                    // Status check needs volatile read
                    while (core::ptr::read_volatile(&spi.STATUS) & pac::spi::TX_FIFO_FULL_MASK) != 0
                    {
                        core::hint::spin_loop();
                    }
                    // TX_DATA write needs to be volatile
                    core::ptr::write_volatile(&mut spi.TX_DATA, (*words.add(i)).to_be());

                    // Status and RX_DATA reads need to be volatile
                    while (core::ptr::read_volatile(&spi.STATUS) & pac::spi::RX_FIFO_EMPTY_MASK)
                        != 0
                    {
                        core::hint::spin_loop();
                    }
                    *words.add(i) = core::ptr::read_volatile(&spi.RX_DATA).to_be();
                }

                // Wait until transfer done - needs volatile read
                while (core::ptr::read_volatile(&spi.STATUS) & pac::spi::ACTIVE_MASK) != 0 {
                    core::hint::spin_loop();
                }

                // Reset state - single write is fine
                spi.COMMAND |= pac::spi::TX_FIFO_RESET_MASK | pac::spi::RX_FIFO_RESET_MASK;
                spi.CONTROL &= !pac::spi::CTRL_ENABLE_MASK;
                core::sync::atomic::fence(core::sync::atomic::Ordering::SeqCst);
            }

            let data = &mut data[word_count as usize * 4..];

            if !data.is_empty() {
                // Setup registers - single volatile write for initial setup
                spi.FRAMESIZE = 8;
                spi.FRAMESUP = data.len() as u32 & pac::spi::BYTESUPPER_MASK;
                let control = (spi.CONTROL & !pac::spi::TXRXDFCOUNT_MASK)
                    | (((data.len() as u32) << pac::spi::TXRXDFCOUNT_SHIFT)
                        & pac::spi::TXRXDFCOUNT_MASK);
                spi.CONTROL = control | pac::spi::CTRL_ENABLE_MASK;
                core::sync::atomic::fence(core::sync::atomic::Ordering::SeqCst);

                // Flush the receive FIFO - needs volatile read
                while (core::ptr::read_volatile(&spi.STATUS) & pac::spi::RX_FIFO_EMPTY_MASK) == 0 {
                    let _ = core::ptr::read_volatile(&spi.RX_DATA);
                }

                for i in 0..data.len() {
                    // Status check needs volatile read
                    while (core::ptr::read_volatile(&spi.STATUS) & pac::spi::TX_FIFO_FULL_MASK) != 0
                    {
                        core::hint::spin_loop();
                    }
                    // TX_DATA write needs to be volatile
                    core::ptr::write_volatile(&mut spi.TX_DATA, data[i] as u32);

                    // Status and RX_DATA reads need to be volatile
                    while (core::ptr::read_volatile(&spi.STATUS) & pac::spi::RX_FIFO_EMPTY_MASK)
                        != 0
                    {
                        core::hint::spin_loop();
                    }
                    data[i] = core::ptr::read_volatile(&spi.RX_DATA) as u8;
                }

                // Wait until transfer done - needs volatile read
                while (core::ptr::read_volatile(&spi.STATUS) & pac::spi::ACTIVE_MASK) != 0 {
                    core::hint::spin_loop();
                }

                // Reset state - single write is fine
                spi.COMMAND |= pac::spi::TX_FIFO_RESET_MASK | pac::spi::RX_FIFO_RESET_MASK;
                spi.CONTROL &= !pac::spi::CTRL_ENABLE_MASK;
                core::sync::atomic::fence(core::sync::atomic::Ordering::SeqCst);
            }
        }

        Ok(())
    }
}