Skip to main content

nrf52/
uarte.rs

1// Licensed under the Apache License, Version 2.0 or the MIT License.
2// SPDX-License-Identifier: Apache-2.0 OR MIT
3// Copyright Tock Contributors 2022.
4
5//! Universal asynchronous receiver/transmitter with EasyDMA (UARTE)
6//!
7//! Author
8//! -------------------
9//!
10//! * Author: Niklas Adolfsson <niklasadolfsson1@gmail.com>
11//! * Date: March 10 2018
12
13use core::cell::Cell;
14use kernel::ErrorCode;
15use kernel::hil::uart;
16use kernel::utilities::StaticRef;
17use kernel::utilities::cells::{MapCell, OptionalCell};
18use kernel::utilities::dma_slice::DmaSubSliceMut;
19use kernel::utilities::leasable_buffer::SubSliceMut;
20use nrf5x::gpio::Pin;
21use nrf5x::pinmux;
22use tock_registers_v0::interfaces::{Readable, Writeable};
23use tock_registers_v0::registers::{ReadOnly, ReadWrite, WriteOnly};
24use tock_registers_v0::{register_bitfields, register_structs};
25
26const UARTE_MAX_BUFFER_SIZE: usize = 0xff;
27
28pub const UARTE0_BASE: StaticRef<crate::uarte::UarteRegisters> =
29    unsafe { StaticRef::new(0x40002000 as *const crate::uarte::UarteRegisters) };
30
31register_structs! {
32    pub UarteRegisters {
33        (0x000 => task_startrx: WriteOnly<u32, Task::Register>),
34        (0x004 => task_stoprx: WriteOnly<u32, Task::Register>),
35        (0x008 => task_starttx: WriteOnly<u32, Task::Register>),
36        (0x00C => task_stoptx: WriteOnly<u32, Task::Register>),
37        (0x010 => _reserved1),
38        (0x02C => task_flush_rx: WriteOnly<u32, Task::Register>),
39        (0x030 => _reserved2),
40        (0x100 => event_cts: ReadWrite<u32, Event::Register>),
41        (0x104 => event_ncts: ReadWrite<u32, Event::Register>),
42        (0x108 => _reserved3),
43        (0x110 => event_endrx: ReadWrite<u32, Event::Register>),
44        (0x114 => _reserved4),
45        (0x120 => event_endtx: ReadWrite<u32, Event::Register>),
46        (0x124 => event_error: ReadWrite<u32, Event::Register>),
47        (0x128 => _reserved6),
48        (0x144 => event_rxto: ReadWrite<u32, Event::Register>),
49        (0x148 => _reserved7),
50        (0x14C => event_rxstarted: ReadWrite<u32, Event::Register>),
51        (0x150 => event_txstarted: ReadWrite<u32, Event::Register>),
52        (0x154 => _reserved8),
53        (0x158 => event_txstopped: ReadWrite<u32, Event::Register>),
54        (0x15C => _reserved9),
55        (0x200 => shorts: ReadWrite<u32, Shorts::Register>),
56        (0x204 => _reserved10),
57        (0x304 => intenset: ReadWrite<u32, Interrupt::Register>),
58        (0x308 => intenclr: ReadWrite<u32, Interrupt::Register>),
59        (0x30C => _reserved11),
60        (0x480 => errorsrc: ReadWrite<u32, ErrorSrc::Register>),
61        (0x484 => _reserved12),
62        (0x500 => enable: ReadWrite<u32, Uart::Register>),
63        (0x504 => _reserved13),
64        (0x508 => pselrts: ReadWrite<u32, Psel::Register>),
65        (0x50C => pseltxd: ReadWrite<u32, Psel::Register>),
66        (0x510 => pselcts: ReadWrite<u32, Psel::Register>),
67        (0x514 => pselrxd: ReadWrite<u32, Psel::Register>),
68        (0x518 => _reserved14),
69        (0x524 => baudrate: ReadWrite<u32, Baudrate::Register>),
70        (0x528 => _reserved15),
71        (0x534 => rxd_ptr: ReadWrite<u32, Pointer::Register>),
72        (0x538 => rxd_maxcnt: ReadWrite<u32, Counter::Register>),
73        (0x53C => rxd_amount: ReadOnly<u32, Counter::Register>),
74        (0x540 => _reserved16),
75        (0x544 => txd_ptr: ReadWrite<u32, Pointer::Register>),
76        (0x548 => txd_maxcnt: ReadWrite<u32, Counter::Register>),
77        (0x54C => txd_amount: ReadOnly<u32, Counter::Register>),
78        (0x550 => _reserved17),
79        (0x56C => config: ReadWrite<u32, Config::Register>),
80        (0x570 => @END),
81    }
82}
83
84register_bitfields! [u32,
85    /// Start task
86    Task [
87        ENABLE OFFSET(0) NUMBITS(1)
88    ],
89
90    /// Read event
91    Event [
92        READY OFFSET(0) NUMBITS(1)
93    ],
94
95    /// Shortcuts
96    Shorts [
97        // Shortcut between ENDRX and STARTRX
98        ENDRX_STARTRX OFFSET(5) NUMBITS(1),
99        // Shortcut between ENDRX and STOPRX
100        ENDRX_STOPRX OFFSET(6) NUMBITS(1)
101    ],
102
103    /// UART Interrupts
104    Interrupt [
105        CTS OFFSET(0) NUMBITS(1),
106        NCTS OFFSET(1) NUMBITS(1),
107        ENDRX OFFSET(4) NUMBITS(1),
108        ENDTX OFFSET(8) NUMBITS(1),
109        ERROR OFFSET(9) NUMBITS(1),
110        RXTO OFFSET(17) NUMBITS(1),
111        RXSTARTED OFFSET(19) NUMBITS(1),
112        TXSTARTED OFFSET(20) NUMBITS(1),
113        TXSTOPPED OFFSET(22) NUMBITS(1)
114    ],
115
116    /// UART Errors
117    ErrorSrc [
118        OVERRUN OFFSET(0) NUMBITS(1),
119        PARITY OFFSET(1) NUMBITS(1),
120        FRAMING OFFSET(2) NUMBITS(1),
121        BREAK OFFSET(3) NUMBITS(1)
122    ],
123
124    /// Enable UART
125    Uart [
126        ENABLE OFFSET(0) NUMBITS(4) [
127            ON = 8,
128            OFF = 0
129        ]
130    ],
131
132    /// Pin select
133    Psel [
134        // Pin number. MSB is actually the port indicator, but since we number
135        // pins sequentially the binary representation of the pin number has
136        // the port bit set correctly. So, for simplicity we just treat the
137        // pin number as a 6 bit field.
138        PIN OFFSET(0) NUMBITS(6),
139        // Connect/Disconnect
140        CONNECT OFFSET(31) NUMBITS(1)
141    ],
142
143    /// Baudrate
144    Baudrate [
145        BAUDRAUTE OFFSET(0) NUMBITS(32)
146    ],
147
148    /// DMA pointer
149    Pointer [
150        POINTER OFFSET(0) NUMBITS(32)
151    ],
152
153    /// Counter value
154    Counter [
155        COUNTER OFFSET(0) NUMBITS(8)
156    ],
157
158    /// Configuration of parity and flow control
159    Config [
160        HWFC OFFSET(0) NUMBITS(1),
161        PARITY OFFSET(1) NUMBITS(3)
162    ]
163];
164
165/// Wrapper for managing MMIO for UARTE.
166pub struct UarteRegistersManager {
167    /// MMIO registers for the UARTE peripheral.
168    registers: StaticRef<UarteRegisters>,
169    /// Holding place for the TX DMA buffer while DMA in progress.
170    tx_dma_buf: MapCell<DmaSubSliceMut<'static, u8>>,
171    /// Holding place for the RX DMA buffer while DMA in progress.
172    rx_dma_buf: MapCell<DmaSubSliceMut<'static, u8>>,
173}
174
175impl UarteRegistersManager {
176    /// Create a DMA-enabled register manager for UARTE.
177    ///
178    /// # Safety
179    ///
180    /// This controls DMA hardware. As such, it must be unique. This requires:
181    ///
182    /// - This constructor must be called at most once.
183    /// - There must not be any other code that accesses the DMA buffer and
184    ///   length registers.
185    pub unsafe fn new_uarte0() -> Self {
186        Self {
187            registers: UARTE0_BASE,
188            tx_dma_buf: MapCell::empty(),
189            rx_dma_buf: MapCell::empty(),
190        }
191    }
192
193    /// Start a UART transmission with DMA.
194    ///
195    /// # Return
196    ///
197    /// `Ok(())` on successfully starting the DMA operation. `Err(())` if the
198    /// DMA is busy and the operation could not be started.
199    pub fn start_tx_dma(&self, buf: SubSliceMut<'static, u8>) -> Result<(), ()> {
200        if self.tx_dma_pending() {
201            return Err(());
202        }
203
204        // To create a DmaFence we must trust the implementation.
205        //
206        // # Safety
207        //
208        // The architecture-provided version is correct for the nRF52.
209        let fence = unsafe { cortexm4f::dma_fence::CortexMDmaFence::new() };
210
211        // Create DmaSlice for the TX buffer. This ensures that we can soundly
212        // share it with the DMA hardware.
213        let tx_dma_slice = DmaSubSliceMut::new_static(buf, fence);
214
215        // Provide the DmaSlice buffer to the hardware DMA engine.
216        self.registers.txd_ptr.set(tx_dma_slice.ptr_addr() as u32);
217
218        // Specify the length to transmit.
219        self.registers
220            .txd_maxcnt
221            .write(Counter::COUNTER.val(tx_dma_slice.len() as u32));
222
223        // Save the DmaSlice while the DMA operation executes.
224        self.tx_dma_buf.replace(tx_dma_slice);
225
226        // Start the TX DMA operation
227        self.registers.task_starttx.write(Task::ENABLE::SET);
228
229        Ok(())
230    }
231
232    pub fn finish_tx_dma(&self) -> Option<(SubSliceMut<'static, u8>, usize)> {
233        // End the DMA operation so it is safe to retrieve the buffer.
234        self.registers.event_endtx.write(Event::READY::CLEAR);
235
236        self.tx_dma_buf.take().map(|dma_slice| {
237            // To create a DmaFence we must trust the implementation.
238            //
239            // # Safety
240            //
241            // The architecture-provided version is correct for the nRF52.
242            let fence = unsafe { cortexm4f::dma_fence::CortexMDmaFence::new() };
243
244            // # Safety
245            //
246            // We must ensure that the DMA hardware no longer has any access
247            // to this buffer. We ensure that by setting the `event_endtx`
248            // event before taking the dma slice back.
249            let buf = unsafe { dma_slice.take(fence) };
250
251            let tx_bytes = self.registers.txd_amount.get() as usize;
252
253            (buf, tx_bytes)
254        })
255    }
256
257    pub fn tx_dma_pending(&self) -> bool {
258        self.tx_dma_buf.is_some()
259    }
260
261    /// Start a UART reception with DMA.
262    ///
263    /// # Return
264    ///
265    /// `Ok(())` on successfully starting the DMA operation. `Err(())` if the
266    /// DMA is busy and the operation could not be started.
267    pub fn start_rx_dma(&self, buf: SubSliceMut<'static, u8>) -> Result<(), ()> {
268        if self.rx_dma_pending() {
269            return Err(());
270        }
271
272        // To create a DmaFence we must trust the implementation.
273        //
274        // # Safety
275        //
276        // The architecture-provided version is correct for the nRF52.
277        let fence = unsafe { cortexm4f::dma_fence::CortexMDmaFence::new() };
278
279        // Create DmaSlice for the RX buffer. This ensures that we can soundly
280        // share it with the DMA hardware.
281        let rx_dma_slice = DmaSubSliceMut::new_static(buf, fence);
282
283        // Provide the DmaSlice buffer to the hardware DMA engine.
284        self.registers.rxd_ptr.set(rx_dma_slice.ptr_addr() as u32);
285
286        // Specify the length to transmit.
287        self.registers
288            .rxd_maxcnt
289            .write(Counter::COUNTER.val(rx_dma_slice.len() as u32));
290
291        // Save the DmaSlice while the DMA operation executes.
292        self.rx_dma_buf.replace(rx_dma_slice);
293
294        // Start the RX DMA operation
295        self.registers.task_startrx.write(Task::ENABLE::SET);
296
297        Ok(())
298    }
299
300    pub fn finish_rx_dma(&self) -> Option<(SubSliceMut<'static, u8>, usize)> {
301        // End the DMA operation so it is safe to retrieve the buffer.
302        self.registers.event_endrx.write(Event::READY::CLEAR);
303
304        self.rx_dma_buf.take().map(|dma_slice| {
305            // To create a DmaFence we must trust the implementation.
306            //
307            // # Safety
308            //
309            // The architecture-provided version is correct for the nRF52.
310            let fence = unsafe { cortexm4f::dma_fence::CortexMDmaFence::new() };
311
312            // # Safety
313            //
314            // We must ensure that the DMA hardware no longer has any access
315            // to this buffer. We ensure that by setting the `event_endrx`
316            // event before taking the dma slice back.
317            let buf = unsafe { dma_slice.take(fence) };
318
319            let rx_bytes = self.registers.rxd_amount.get() as usize;
320
321            (buf, rx_bytes)
322        })
323    }
324
325    pub fn rx_dma_pending(&self) -> bool {
326        self.rx_dma_buf.is_some()
327    }
328}
329
330/// UARTE
331// It should never be instanced outside this module but because a static mutable reference to it
332// is exported outside this module it must be `pub`
333pub struct Uarte<'a> {
334    registers: UarteRegistersManager,
335    tx_client: OptionalCell<&'a dyn uart::TransmitClient>,
336    tx_len: Cell<usize>,
337    rx_client: OptionalCell<&'a dyn uart::ReceiveClient>,
338    rx_len: Cell<usize>,
339    rx_abort_in_progress: Cell<bool>,
340}
341
342#[derive(Copy, Clone)]
343pub struct UARTParams {
344    pub baud_rate: u32,
345}
346
347impl<'a> Uarte<'a> {
348    /// Constructor
349    // This should only be constructed once
350    pub fn new(registers: UarteRegistersManager) -> Uarte<'a> {
351        Uarte {
352            registers,
353            tx_client: OptionalCell::empty(),
354            // tx_buffer: kernel::utilities::cells::TakeCell::empty(),
355            tx_len: Cell::new(0),
356            // tx_remaining_bytes: Cell::new(0),
357            rx_client: OptionalCell::empty(),
358            rx_len: Cell::new(0),
359            rx_abort_in_progress: Cell::new(false),
360        }
361    }
362
363    fn initialize_inner(&self, txd: Pin, rxd: Pin, cts: Option<Pin>, rts: Option<Pin>) {
364        self.disable_uart();
365
366        // Stop any ongoing TX or RX DMA transmissions
367        self.registers
368            .registers
369            .task_stoptx
370            .write(Task::ENABLE::SET);
371        self.registers
372            .registers
373            .task_stoprx
374            .write(Task::ENABLE::SET);
375
376        // Make sure we clear the endtx and endrx interrupts since
377        // that is what we rely on to know when the DMA TX
378        // finishes. Normally, we clear this interrupt as we handle
379        // it, so this is not necessary. However, a bootloader (or
380        // some other startup code) may have setup TX interrupts, and
381        // there may be one pending. We clear it to be safe.
382        self.registers
383            .registers
384            .event_endtx
385            .write(Event::READY::CLEAR);
386        self.registers
387            .registers
388            .event_endrx
389            .write(Event::READY::CLEAR);
390
391        self.registers
392            .registers
393            .pseltxd
394            .write(Psel::PIN.val(txd as _));
395        self.registers
396            .registers
397            .pselrxd
398            .write(Psel::PIN.val(rxd as _));
399        cts.map_or_else(
400            || {
401                // If no CTS pin is provided, then we need to mark it as
402                // disconnected in the register.
403                self.registers.registers.pselcts.write(Psel::CONNECT::SET);
404            },
405            |c| {
406                self.registers
407                    .registers
408                    .pselcts
409                    .write(Psel::PIN.val(c as _));
410            },
411        );
412        rts.map_or_else(
413            || {
414                // If no RTS pin is provided, then we need to mark it as
415                // disconnected in the register.
416                self.registers.registers.pselrts.write(Psel::CONNECT::SET);
417            },
418            |r| {
419                self.registers
420                    .registers
421                    .pselrts
422                    .write(Psel::PIN.val(r as _));
423            },
424        );
425
426        self.enable_uart();
427    }
428
429    /// Configure which pins the UART should use for txd, rxd, cts and rts
430    pub fn initialize(
431        &self,
432        txd: pinmux::Pinmux,
433        rxd: pinmux::Pinmux,
434        cts: Option<pinmux::Pinmux>,
435        rts: Option<pinmux::Pinmux>,
436    ) {
437        self.initialize_inner(
438            txd.into(),
439            rxd.into(),
440            cts.map(Into::into),
441            rts.map(Into::into),
442        )
443    }
444
445    // The datasheet gives a non-exhaustive list of example settings for
446    // typical bauds. The register is actually just a simple clock divider,
447    // as explained and with implementation from:
448    // https://devzone.nordicsemi.com/f/nordic-q-a/43280/technical-question-regarding-uart-baud-rate-generator-baudrate-register-offset-0x524
449    //
450    // Technically only RX is limited to 1MBaud, can TX up to 8MBaud:
451    // https://devzone.nordicsemi.com/f/nordic-q-a/84204/framing-error-and-noisy-data-when-using-uarte-at-high-baud-rate
452    pub fn get_divider_for_baud(baud_rate: u32) -> Result<u32, ErrorCode> {
453        if baud_rate > 1_000_000 || baud_rate < 1200 {
454            return Err(ErrorCode::INVAL);
455        }
456
457        // force 64 bit values for precision
458        let system_clock = 16000000u64; // TODO: Support dynamic clock
459        let scalar = 32u64;
460        let target_baud: u64 = baud_rate.into();
461
462        // n.b. bits 11-0 are ignored by hardware
463        let divider64 = (((target_baud << scalar) + (system_clock >> 1)) / system_clock) + 0x800;
464        let divider = (divider64 & 0xffff_f000) as u32;
465
466        Ok(divider)
467    }
468
469    fn set_baud_rate(&self, baud_rate: u32) -> Result<(), ErrorCode> {
470        let divider = Self::get_divider_for_baud(baud_rate)?;
471        self.registers.registers.baudrate.set(divider);
472
473        Ok(())
474    }
475
476    // Enable UART peripheral, this need to disabled for low power applications
477    fn enable_uart(&self) {
478        self.registers.registers.enable.write(Uart::ENABLE::ON);
479    }
480
481    #[allow(dead_code)]
482    fn disable_uart(&self) {
483        self.registers.registers.enable.write(Uart::ENABLE::OFF);
484    }
485
486    fn enable_rx_interrupts(&self) {
487        self.registers
488            .registers
489            .intenset
490            .write(Interrupt::ENDRX::SET);
491    }
492
493    fn enable_tx_interrupts(&self) {
494        self.registers
495            .registers
496            .intenset
497            .write(Interrupt::ENDTX::SET);
498    }
499
500    fn disable_rx_interrupts(&self) {
501        self.registers
502            .registers
503            .intenclr
504            .write(Interrupt::ENDRX::SET);
505    }
506
507    fn disable_tx_interrupts(&self) {
508        self.registers
509            .registers
510            .intenclr
511            .write(Interrupt::ENDTX::SET);
512    }
513
514    /// UART interrupt handler that listens for both tx_end and rx_end events
515    #[inline(never)]
516    pub fn handle_interrupt(&self) {
517        if self.tx_ready() {
518            self.disable_tx_interrupts();
519
520            if let Some((mut buf, transmitted_length)) = self.registers.finish_tx_dma() {
521                let active_range = buf.active_range();
522
523                // Calculate the remaining bytes to transmit based on the length to
524                // transmit, the window we just tried to transmit, and how many
525                // bytes we actually did transmit.
526                //
527                // <-----buffer------------------->
528                //          <-active range->
529                // [        [              ]      ]
530                let remaining_bytes = self
531                    .tx_len
532                    .get()
533                    .saturating_sub(active_range.start)
534                    .saturating_sub(transmitted_length);
535
536                if remaining_bytes == 0 {
537                    // We sent everything.
538                    self.tx_client.map(|client| {
539                        client.transmitted_buffer(buf.take(), self.tx_len.get(), Ok(()));
540                    });
541                } else {
542                    // Send the next portion of the buffer.
543
544                    // Reset back to the original slice.
545                    buf.reset();
546                    // Limit to just the portion of the buffer we are transmitting from.
547                    buf.slice(0..self.tx_len.get());
548                    // Skip what has already been transmitted.
549                    buf.slice((self.tx_len.get() - remaining_bytes)..);
550                    // Limit to at most the `UARTE_MAX_BUFFER_SIZE` bytes.
551                    buf.slice(0..UARTE_MAX_BUFFER_SIZE);
552                    // Send via DMA.
553                    let _ = self.registers.start_tx_dma(buf);
554                    // Re-enable interrupts.
555                    self.enable_tx_interrupts();
556                }
557            }
558        }
559
560        if self.rx_ready() {
561            self.disable_rx_interrupts();
562
563            // Clear the ENDRX event
564            self.registers
565                .registers
566                .event_endrx
567                .write(Event::READY::CLEAR);
568
569            if let Some((mut buf, received_length)) = self.registers.finish_rx_dma() {
570                let active_range = buf.active_range();
571
572                // Check if this ENDRX is due to an abort. If so, we want to
573                // do the receive callback immediately.
574                if self.rx_abort_in_progress.get() {
575                    self.rx_abort_in_progress.set(false);
576
577                    // Calculate how many bytes we actually received.
578                    let received_bytes = active_range.start + received_length;
579
580                    // Notify the client.
581                    self.rx_client.map(|client| {
582                        client.received_buffer(
583                            buf.take(),
584                            received_bytes,
585                            Err(ErrorCode::CANCEL),
586                            uart::Error::None,
587                        );
588                    });
589                } else {
590                    // In the normal case, we need to either pass call the callback
591                    // or do another read to get more bytes.
592
593                    // Calculate the remaining bytes to receive based on the length to
594                    // receive, the window we just tried to receive into, and how many
595                    // bytes we actually did receive.
596                    //
597                    //
598                    // <-----buffer------------------->
599                    //          <-active range->
600                    // [        [              ]      ]
601                    let remaining_bytes = self
602                        .rx_len
603                        .get()
604                        .saturating_sub(active_range.start)
605                        .saturating_sub(received_length);
606
607                    if remaining_bytes == 0 {
608                        // Signal client that the read is done
609                        self.rx_client.map(|client| {
610                            client.received_buffer(
611                                buf.take(),
612                                self.rx_len.get(),
613                                Ok(()),
614                                uart::Error::None,
615                            );
616                        });
617                    } else {
618                        // Receive into the next portion of the buffer.
619
620                        // Reset back to the original slice.
621                        buf.reset();
622                        // Limit to just the portion of the buffer we are receiving into.
623                        buf.slice(0..self.rx_len.get());
624                        // Skip what has already been received.
625                        buf.slice((self.rx_len.get() - remaining_bytes)..);
626                        // Limit to at most the `UARTE_MAX_BUFFER_SIZE` bytes.
627                        buf.slice(0..UARTE_MAX_BUFFER_SIZE);
628                        // Receive via DMA.
629                        let _ = self.registers.start_rx_dma(buf);
630                        // Re-enable interrupts.
631                        self.enable_rx_interrupts();
632                    }
633                }
634            }
635        }
636    }
637
638    /// Check if the UART transmission is done
639    pub fn tx_ready(&self) -> bool {
640        self.registers.registers.event_endtx.is_set(Event::READY)
641    }
642
643    /// Check if either the rx_buffer is full or the UART has timed out
644    pub fn rx_ready(&self) -> bool {
645        self.registers.registers.event_endrx.is_set(Event::READY)
646    }
647
648    // Helper function used by both transmit_word and transmit_buffer
649    fn setup_buffer_transmit(&self, buf: &'static mut [u8], tx_len: usize) {
650        // Save the total length to transmit as we may need to send over
651        // multiple iterations.
652        self.tx_len.set(tx_len);
653
654        // Create a `SubSlice` to simplify tracking which part we are sending,
655        // and slice the sub slice to either the total buffer to send or what
656        // fits in one send buffer.
657        let mut slice_to_send = SubSliceMut::new(buf);
658        slice_to_send.slice(0..core::cmp::min(tx_len, UARTE_MAX_BUFFER_SIZE));
659
660        // Send the buffer using DMA. This is managed by the register manager to
661        // ensure we are safely using DMA.
662        let _ = self.registers.start_tx_dma(slice_to_send);
663
664        // Enable interrupts so we get a interrupt when the transmission has
665        // finished.
666        self.enable_tx_interrupts();
667    }
668
669    fn setup_buffer_receive(&self, buf: &'static mut [u8], rx_len: usize) {
670        // Save the total length to receive.
671        self.rx_len.set(rx_len);
672
673        // Create a `SubSlice` to simplify tracking which part we have received
674        // into.
675        let mut slice_to_receive = SubSliceMut::new(buf);
676        slice_to_receive.slice(0..core::cmp::min(rx_len, UARTE_MAX_BUFFER_SIZE));
677
678        // Use the buffer with DMA. This is managed by the register manager to
679        // ensure we are safely using DMA.
680        let _ = self.registers.start_rx_dma(slice_to_receive);
681
682        // Enable interrupts so we get a interrupt when the receive has
683        // finished.
684        self.enable_rx_interrupts();
685    }
686}
687
688impl<'a> uart::Transmit<'a> for Uarte<'a> {
689    fn set_transmit_client(&self, client: &'a dyn uart::TransmitClient) {
690        self.tx_client.set(client);
691    }
692
693    fn transmit_buffer(
694        &self,
695        tx_data: &'static mut [u8],
696        tx_len: usize,
697    ) -> Result<(), (ErrorCode, &'static mut [u8])> {
698        if tx_len == 0 || tx_len > tx_data.len() {
699            Err((ErrorCode::SIZE, tx_data))
700        } else if self.registers.tx_dma_pending() {
701            Err((ErrorCode::BUSY, tx_data))
702        } else {
703            self.setup_buffer_transmit(tx_data, tx_len);
704            Ok(())
705        }
706    }
707
708    fn transmit_word(&self, _data: u32) -> Result<(), ErrorCode> {
709        Err(ErrorCode::FAIL)
710    }
711
712    fn transmit_abort(&self) -> Result<(), ErrorCode> {
713        Err(ErrorCode::FAIL)
714    }
715}
716
717impl uart::Configure for Uarte<'_> {
718    fn configure(&self, params: uart::Parameters) -> Result<(), ErrorCode> {
719        // These could probably be implemented, but are currently ignored, so
720        // throw an error.
721        if params.stop_bits != uart::StopBits::One {
722            return Err(ErrorCode::NOSUPPORT);
723        }
724        if params.parity != uart::Parity::None {
725            return Err(ErrorCode::NOSUPPORT);
726        }
727        if params.hw_flow_control {
728            return Err(ErrorCode::NOSUPPORT);
729        }
730
731        self.set_baud_rate(params.baud_rate)?;
732
733        Ok(())
734    }
735}
736
737impl<'a> uart::Receive<'a> for Uarte<'a> {
738    fn set_receive_client(&self, client: &'a dyn uart::ReceiveClient) {
739        self.rx_client.set(client);
740    }
741
742    fn receive_buffer(
743        &self,
744        rx_buf: &'static mut [u8],
745        rx_len: usize,
746    ) -> Result<(), (ErrorCode, &'static mut [u8])> {
747        if rx_len > rx_buf.len() {
748            Err((ErrorCode::SIZE, rx_buf))
749        } else if self.registers.rx_dma_pending() {
750            Err((ErrorCode::BUSY, rx_buf))
751        } else {
752            self.setup_buffer_receive(rx_buf, rx_len);
753            Ok(())
754        }
755    }
756
757    fn receive_word(&self) -> Result<(), ErrorCode> {
758        Err(ErrorCode::FAIL)
759    }
760
761    fn receive_abort(&self) -> Result<(), ErrorCode> {
762        // Trigger the STOPRX event to cancel the current receive call.
763        if !self.registers.rx_dma_pending() {
764            Ok(())
765        } else {
766            self.rx_abort_in_progress.set(true);
767            self.registers
768                .registers
769                .task_stoprx
770                .write(Task::ENABLE::SET);
771            Err(ErrorCode::BUSY)
772        }
773    }
774}
775
776#[cfg(test)]
777mod tests {
778    use kernel::ErrorCode;
779
780    #[test]
781    fn baud_rate_divider_calculation() {
782        use crate::uarte::Uarte;
783
784        assert_eq!(Uarte::get_divider_for_baud(0), Err(ErrorCode::INVAL));
785        assert_eq!(
786            Uarte::get_divider_for_baud(4_000_000),
787            Err(ErrorCode::INVAL)
788        );
789
790        // The constants below are the list from the Nordic technical documents.
791        //
792        // n.b., some datasheet constants do not match formula constants,
793        // so we skip those, see nordic forum thread for details:
794        // https://devzone.nordicsemi.com/f/nordic-q-a/84204/framing-error-and-noisy-data-when-using-uarte-at-high-baud-rate
795        //
796        // This is a *datasheet bug*, i.e., for a target baud of 115200, the
797        // datasheet divisor yields 115108 (-0.079% err) where direct
798        // computation of the divider yields 115203 (+0.002% err). Both work in
799        // practice, but the error here is an annoying and uncharacteristic
800        // Nordic quirk.
801        assert_eq!(Uarte::get_divider_for_baud(1200), Ok(0x0004F000));
802        assert_eq!(Uarte::get_divider_for_baud(2400), Ok(0x0009D000));
803        assert_eq!(Uarte::get_divider_for_baud(4800), Ok(0x0013B000));
804        assert_eq!(Uarte::get_divider_for_baud(9600), Ok(0x00275000));
805        //assert_eq!(u.get_divider_for_baud(14400), Ok(0x003AF000));
806        assert_eq!(Uarte::get_divider_for_baud(19200), Ok(0x004EA000));
807        //assert_eq!(u.get_divider_for_baud(28800), Ok(0x0075C000));
808        //assert_eq!(u.get_divider_for_baud(38400), Ok(0x009D0000));
809        //assert_eq!(u.get_divider_for_baud(57600), Ok(0x00EB0000));
810        assert_eq!(Uarte::get_divider_for_baud(76800), Ok(0x013A9000));
811        //assert_eq!(u.get_divider_for_baud(115200), Ok(0x01D60000));
812        //assert_eq!(u.get_divider_for_baud(230400), Ok(0x03B00000));
813        assert_eq!(Uarte::get_divider_for_baud(250000), Ok(0x04000000));
814        //assert_eq!(u.get_divider_for_baud(460800), Ok(0x07400000));
815        //assert_eq!(u.get_divider_for_baud(921600), Ok(0x0F000000));
816        assert_eq!(Uarte::get_divider_for_baud(1000000), Ok(0x10000000));
817        //
818        // For completeness of testing, we do verify that the calculation works
819        // as-expected to generate the empirically correct divisors.  (i.e.,
820        // these are not the datasheet constants, but are the correct divisors
821        // for the desired bauds):
822        assert_eq!(Uarte::get_divider_for_baud(14400), Ok(0x003B0000));
823        assert_eq!(Uarte::get_divider_for_baud(28800), Ok(0x0075F000));
824        assert_eq!(Uarte::get_divider_for_baud(38400), Ok(0x009D5000));
825        assert_eq!(Uarte::get_divider_for_baud(57600), Ok(0x00EBF000));
826        assert_eq!(Uarte::get_divider_for_baud(115200), Ok(0x01D7E000));
827        assert_eq!(Uarte::get_divider_for_baud(230400), Ok(0x03AFB000));
828        assert_eq!(Uarte::get_divider_for_baud(460800), Ok(0x075F7000));
829        assert_eq!(Uarte::get_divider_for_baud(921600), Ok(0x0EBEE000));
830    }
831}