Skip to main content

capsules_extra/usb/
cdc.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//! Communications Class Device for USB
6//!
7//! This capsule allows Tock to support a serial port over USB.
8
9use core::cell::Cell;
10use core::cmp;
11
12use super::descriptors;
13use super::descriptors::Buffer64;
14use super::descriptors::CdcInterfaceDescriptor;
15use super::descriptors::Descriptor;
16use super::descriptors::EndpointAddress;
17use super::descriptors::EndpointDescriptor;
18use super::descriptors::InterfaceDescriptor;
19use super::descriptors::TransferDirection;
20use super::usbc_client_ctrl::ClientCtrl;
21
22use kernel::ErrorCode;
23use kernel::deferred_call::{DeferredCall, DeferredCallClient};
24use kernel::hil;
25use kernel::hil::time::{Alarm, AlarmClient, ConvertTicks};
26use kernel::hil::uart;
27use kernel::hil::usb::TransferType;
28use kernel::utilities::cells::OptionalCell;
29use kernel::utilities::cells::TakeCell;
30use tock_registers_v0::interfaces::{Readable, Writeable};
31use tock_registers_v0::registers::InMemoryRegister;
32
33/// Identifying number for the endpoint when transferring data from us to the
34/// host.
35const ENDPOINT_IN_NUM: usize = 2;
36/// Identifying number for the endpoint when transferring data from the host to
37/// us.
38const ENDPOINT_OUT_NUM: usize = 3;
39
40static LANGUAGES: &[u16; 1] = &[
41    0x0409, // English (United States)
42];
43/// Platform-specific packet length for the `SAM4L` USB hardware.
44pub const MAX_CTRL_PACKET_SIZE_SAM4L: u8 = 8;
45/// Platform-specific packet length for the `nRF52` USB hardware.
46pub const MAX_CTRL_PACKET_SIZE_NRF52840: u8 = 64;
47/// Platform-specific packet length for the `earlgrey` USB hardware.
48pub const MAX_CTRL_PACKET_SIZE_EARLGREY: u8 = 64;
49/// Number of ms to buffer uart transmissions before beginning to drop them.
50///
51/// This is useful in that it allows users time to connect over CDC without losing message,
52/// while still guaranteeing that blocking uart transmissions eventually get a callback even
53/// if a debug output is not connected.
54pub const CDC_BUFFER_TIMEOUT_MS: u32 = 10000;
55
56const N_ENDPOINTS: usize = 3;
57
58/// States of the CDC driver.
59#[derive(Debug, Copy, Clone, PartialEq)]
60enum State {
61    /// Default state. User must call `enable()`.
62    Disabled,
63    /// `enable()` has been called. The descriptor format has been passed to the
64    /// hardware.
65    Enabled,
66    /// `attach()` has been called. The hardware should be ready for a host to
67    /// connect.
68    Attached,
69    /// The host has enumerated this USB device. Things should be functional at
70    /// this point.
71    Enumerated,
72    /// We are seeing the CDC messages that we expect to signal that a CDC
73    /// client has connected. We want to see that both line coding and line
74    /// state ctrl messages have been received. We stay in the "connecting"
75    /// state until the USB transfers for both ctrl messages have completed.
76    Connecting { line_coding: bool, line_state: bool },
77    /// We have seen the necessary setup messages in the `Connecting` state, now
78    /// we delay just to ensure the host has enough time to receive _and
79    /// display_ messages.
80    ConnectingDelay,
81    /// A CDC client is connected. We can safely send data.
82    Connected,
83}
84
85/// States of the Control Endpoint related to CDC-ACM.
86#[derive(Debug, Copy, Clone, PartialEq)]
87enum CtrlState {
88    /// No ongoing ctrl transcation.
89    Idle,
90    /// Host has sent a SET_LINE_CODING configuration request.
91    SetLineCoding,
92    /// Host has sent a GET_LINE_CODING configuration request.
93    GetLineCoding,
94    /// Host has send a SET_CONTROL_LINE_STATE configuration request.
95    SetControlLineState,
96}
97
98#[derive(PartialEq)]
99enum CDCCntrlMessage {
100    NotSupported,
101    SetLineCoding = 0x20,
102    GetLineCoding = 0x21,
103    SetControlLineState = 0x22,
104    SendBreak = 0x23,
105}
106
107impl From<u8> for CDCCntrlMessage {
108    fn from(num: u8) -> Self {
109        match num {
110            0x20 => CDCCntrlMessage::SetLineCoding,
111            0x21 => CDCCntrlMessage::GetLineCoding,
112            0x22 => CDCCntrlMessage::SetControlLineState,
113            0x23 => CDCCntrlMessage::SendBreak,
114            _ => CDCCntrlMessage::NotSupported,
115        }
116    }
117}
118
119/// Implementation of the Abstract Control Model (ACM) for the Communications
120/// Class Device (CDC) over USB.
121pub struct CdcAcm<'a, U: 'a, A: 'a + Alarm<'a>> {
122    /// Helper USB client library for handling many USB operations.
123    client_ctrl: ClientCtrl<'a, 'static, U>,
124
125    /// 64 byte buffers for each endpoint.
126    buffers: [Buffer64; N_ENDPOINTS],
127
128    /// Current state of the CDC driver. This helps us track if a CDC client is
129    /// connected and listening or not.
130    state: Cell<State>,
131
132    /// Current state of the Control Endpoint. This tracks which configuration
133    /// request the host is currently sending us.
134    ctrl_state: Cell<CtrlState>,
135
136    /// A holder reference for the TX buffer we are transmitting from.
137    tx_buffer: TakeCell<'static, [u8]>,
138    /// The number of bytes the client has asked us to send. We track this so we
139    /// can pass it back to the client when the transmission has finished.
140    tx_len: Cell<usize>,
141    /// Where in the `tx_buffer` we need to start sending from when we continue.
142    tx_offset: Cell<usize>,
143    /// The TX client to use when transmissions finish.
144    tx_client: OptionalCell<&'a dyn uart::TransmitClient>,
145
146    /// A holder for the buffer to receive bytes into. We use this as a flag as
147    /// well, if we have a buffer then we are actively doing a receive.
148    rx_buffer: TakeCell<'static, [u8]>,
149    /// How many bytes the client wants us to receive.
150    rx_len: Cell<usize>,
151    /// How many bytes we have received so far.
152    rx_offset: Cell<usize>,
153    /// The RX client to use when RX data is received.
154    rx_client: OptionalCell<&'a dyn uart::ReceiveClient>,
155
156    /// Alarm used to indicate that data should be dropped and callbacks
157    /// returned.
158    timeout_alarm: &'a A,
159    /// Used to track whether we are in the initial boot up period during which
160    /// messages can be queued despite a CDC host not being connected (which is
161    /// useful for ensuring debug messages early in the boot process can be
162    /// delivered over the console).
163    boot_period: Cell<bool>,
164
165    /// Deferred Call
166    deferred_call: DeferredCall,
167    /// Flag to mark we are waiting on a deferred call for dropping a TX. This
168    /// can happen if an upper layer told us to transmit a buffer, but there is
169    /// no host connected and therefore we cannot actually transmit. However,
170    /// normal UART semantics are that we can always send (perhaps with a
171    /// delay), even if nothing is actually listening. To keep the upper layers
172    /// happy and to allow this CDC layer to just drop messages, we always
173    /// return Ok(()) for TX, and then use a deferred call to signal the
174    /// transmit done callback.
175    deferred_call_pending_droptx: Cell<bool>,
176    /// Flag to mark we need a deferred call to signal a callback after an RX
177    /// abort occurs.
178    deferred_call_pending_abortrx: Cell<bool>,
179
180    /// Optional host-initiated function. This function (if supplied) is called
181    /// when the host sends a special message to the device. The normal signal
182    /// for calling this function is the host configuring the baud rate to be
183    /// 1200 baud.
184    ///
185    /// This was originally added for the bootloader to allow the host to tell
186    /// the device to enter bootloader mode.
187    host_initiated_function: Option<&'a (dyn Fn() + 'a)>,
188}
189
190impl<'a, U: hil::usb::UsbController<'a>, A: 'a + Alarm<'a>> CdcAcm<'a, U, A> {
191    pub fn new(
192        controller: &'a U,
193        max_ctrl_packet_size: u8,
194        vendor_id: u16,
195        product_id: u16,
196        strings: &'static [&'static str; 3],
197        timeout_alarm: &'a A,
198        host_initiated_function: Option<&'a (dyn Fn() + 'a)>,
199    ) -> Self {
200        let interfaces: &mut [InterfaceDescriptor] = &mut [
201            InterfaceDescriptor {
202                interface_number: 0,
203                interface_class: 0x02,    // CDC communication
204                interface_subclass: 0x02, // abstract control model (ACM)
205                interface_protocol: 0x01, // V.25ter (AT commands)
206                ..InterfaceDescriptor::default()
207            },
208            InterfaceDescriptor {
209                interface_number: 1,
210                interface_class: 0x0a,    // CDC data
211                interface_subclass: 0x00, // none
212                interface_protocol: 0x00, // none
213                ..InterfaceDescriptor::default()
214            },
215        ];
216
217        let cdc_descriptors: &mut [CdcInterfaceDescriptor] = &mut [
218            CdcInterfaceDescriptor {
219                subtype: descriptors::CdcInterfaceDescriptorSubType::Header,
220                field1: 0x10, // CDC
221                field2: 0x11, // CDC
222            },
223            CdcInterfaceDescriptor {
224                subtype: descriptors::CdcInterfaceDescriptorSubType::CallManagement,
225                field1: 0x00, // Capabilities
226                field2: 0x01, // Data interface 1
227            },
228            CdcInterfaceDescriptor {
229                subtype: descriptors::CdcInterfaceDescriptorSubType::AbstractControlManagement,
230                field1: 0x06, // Capabilities
231                field2: 0x00, // unused
232            },
233            CdcInterfaceDescriptor {
234                subtype: descriptors::CdcInterfaceDescriptorSubType::Union,
235                field1: 0x00, // Interface 0
236                field2: 0x01, // Interface 1
237            },
238        ];
239
240        let endpoints: &[&[EndpointDescriptor]] = &[
241            &[EndpointDescriptor {
242                endpoint_address: EndpointAddress::new_const(4, TransferDirection::DeviceToHost),
243                transfer_type: TransferType::Interrupt,
244                max_packet_size: 8,
245                interval: 16,
246            }],
247            &[
248                EndpointDescriptor {
249                    endpoint_address: EndpointAddress::new_const(
250                        2,
251                        TransferDirection::DeviceToHost,
252                    ),
253                    transfer_type: TransferType::Bulk,
254                    max_packet_size: 64,
255                    interval: 0,
256                },
257                EndpointDescriptor {
258                    endpoint_address: EndpointAddress::new_const(
259                        3,
260                        TransferDirection::HostToDevice,
261                    ),
262                    transfer_type: TransferType::Bulk,
263                    max_packet_size: 64,
264                    interval: 0,
265                },
266            ],
267        ];
268
269        let (device_descriptor_buffer, other_descriptor_buffer) =
270            descriptors::create_descriptor_buffers(
271                descriptors::DeviceDescriptor {
272                    vendor_id,
273                    product_id,
274                    manufacturer_string: 1,
275                    product_string: 2,
276                    serial_number_string: 3,
277                    class: 0x2, // Class: CDC
278                    max_packet_size_ep0: max_ctrl_packet_size,
279                    ..descriptors::DeviceDescriptor::default()
280                },
281                descriptors::ConfigurationDescriptor::default(),
282                interfaces,
283                endpoints,
284                None, // No HID descriptor
285                Some(cdc_descriptors),
286            );
287
288        Self {
289            client_ctrl: ClientCtrl::new(
290                controller,
291                device_descriptor_buffer,
292                other_descriptor_buffer,
293                None, // No HID descriptor
294                None, // No report descriptor
295                LANGUAGES,
296                strings,
297            ),
298            buffers: [
299                Buffer64::default(),
300                Buffer64::default(),
301                Buffer64::default(),
302            ],
303            state: Cell::new(State::Disabled),
304            ctrl_state: Cell::new(CtrlState::Idle),
305            tx_buffer: TakeCell::empty(),
306            tx_len: Cell::new(0),
307            tx_offset: Cell::new(0),
308            tx_client: OptionalCell::empty(),
309            rx_buffer: TakeCell::empty(),
310            rx_len: Cell::new(0),
311            rx_offset: Cell::new(0),
312            rx_client: OptionalCell::empty(),
313            timeout_alarm,
314            boot_period: Cell::new(true),
315            deferred_call: DeferredCall::new(),
316            deferred_call_pending_droptx: Cell::new(false),
317            deferred_call_pending_abortrx: Cell::new(false),
318            host_initiated_function,
319        }
320    }
321
322    #[inline]
323    pub fn controller(&self) -> &'a U {
324        self.client_ctrl.controller()
325    }
326
327    #[inline]
328    fn buffer(&'a self, i: usize) -> &'a [InMemoryRegister<u8>; 64] {
329        &self.buffers[i - 1].buf
330    }
331
332    /// This is a helper function used to indicate successful uart transmission to
333    /// a higher layer client despite not actually being connected to a host. Allows
334    /// blocking debug interfaces to function in the same way they do when an actual UART
335    /// interface is in use. This should only be called in an upcall.
336    fn indicate_tx_success(&self) {
337        self.tx_len.set(0);
338        self.tx_offset.set(0);
339        self.tx_client.map(|client| {
340            self.tx_buffer.take().map(|buf| {
341                client.transmitted_buffer(buf, 0, Err(ErrorCode::FAIL));
342            });
343        });
344    }
345
346    /// Helper function to update the connecting state variable as we progress
347    /// through various setup steps that indicate a host is actually connecting
348    /// to our serial port.
349    ///
350    /// - `line_coding`: if true, set. if false, leave to previous value.
351    /// - `line_state`:  if true, set. if false, leave to previous value.
352    fn set_connecting_state(&self, line_coding: bool, line_state: bool) {
353        match self.state.get() {
354            State::Enumerated => {
355                self.state.set(State::Connecting {
356                    line_coding,
357                    line_state,
358                });
359            }
360            State::Connecting {
361                line_coding: old_lc,
362                line_state: old_ls,
363            } => {
364                self.state.set(State::Connecting {
365                    line_coding: if line_coding { true } else { old_lc },
366                    line_state: if line_state { true } else { old_ls },
367                });
368            }
369            _ => {}
370        }
371    }
372}
373
374impl<'a, U: hil::usb::UsbController<'a>, A: 'a + Alarm<'a>> hil::usb::Client<'a>
375    for CdcAcm<'a, U, A>
376{
377    fn enable(&'a self) {
378        // Set up the default control endpoint
379        self.client_ctrl.enable();
380
381        // Setup buffers for IN and OUT data transfer.
382        self.controller()
383            .endpoint_set_in_buffer(ENDPOINT_IN_NUM, self.buffer(ENDPOINT_IN_NUM));
384        self.controller()
385            .endpoint_in_enable(TransferType::Bulk, ENDPOINT_IN_NUM);
386
387        self.controller()
388            .endpoint_set_out_buffer(ENDPOINT_OUT_NUM, self.buffer(ENDPOINT_OUT_NUM));
389        self.controller()
390            .endpoint_out_enable(TransferType::Bulk, ENDPOINT_OUT_NUM);
391
392        self.state.set(State::Enabled);
393
394        self.timeout_alarm.set_alarm(
395            self.timeout_alarm.now(),
396            self.timeout_alarm.ticks_from_ms(CDC_BUFFER_TIMEOUT_MS),
397        );
398    }
399
400    fn attach(&'a self) {
401        self.client_ctrl.attach();
402        self.state.set(State::Attached);
403    }
404
405    fn bus_reset(&'a self) {
406        // We take a bus reset to mean the enumeration has finished.
407        self.state.set(State::Enumerated);
408    }
409
410    /// Handle a Control Setup transaction.
411    ///
412    /// CDC uses special values here, and we can use these to know when a CDC
413    /// client is connected or not.
414    fn ctrl_setup(&'a self, endpoint: usize) -> hil::usb::CtrlSetupResult {
415        descriptors::SetupData::get(&self.client_ctrl.ctrl_buffer.buf).map(|setup_data| {
416            let b_request = setup_data.request_code;
417
418            match CDCCntrlMessage::from(b_request) {
419                CDCCntrlMessage::SetLineCoding => {
420                    self.ctrl_state.set(CtrlState::SetLineCoding);
421                }
422                CDCCntrlMessage::GetLineCoding => {
423                    self.ctrl_state.set(CtrlState::GetLineCoding);
424                }
425                CDCCntrlMessage::SetControlLineState => {
426                    // Bit 0 and 1 of the value (setup_data.value) can be set
427                    // D0: Indicates to DCE if DTE is present or not.
428                    //     - 0 -> Not present
429                    //     - 1 -> Present
430                    // D1: Carrier control for half duplex modems.
431                    //     - 0 -> Deactivate carrier
432                    //     - 1 -> Activate carrier
433                    let _dtr = setup_data.value & 1 == 1;
434
435                    // DTR should tell us if a terminal is connected. However,
436                    // tockloader does not because on some boards the DTR pin is used as
437                    // a way to reset the MCU from a host using standard serial console
438                    // operations.
439                    //
440                    // Ignoring DTR can mean that serial data is sent via USB even if
441                    // nothing is listening. This matches the behavior of a "normal"
442                    // serial port without flow control, which just sends and doesn't
443                    // know if anything is receiving the bytes.
444                    //
445                    // The behavior of DTR is different on windows vs. linux and mac. On
446                    // windows, the SetControlLineState message that is sent when the
447                    // USB device is first enumerated has DTR set to false. On mac and
448                    // linux, that first message has DTR set to true. On all three platforms,
449                    // when tockloader opens the serial port, the SetControlLineState
450                    // message has DTR set to false.
451                    //
452                    // So, to be most compatible, we ignore DTR and just record that a
453                    // SetControlLineState message was sent.
454                    self.set_connecting_state(false, true);
455
456                    self.ctrl_state.set(CtrlState::SetControlLineState);
457                }
458                CDCCntrlMessage::SendBreak => {
459                    // On Mac, we seem to get the SEND_BREAK to signal that a
460                    // client disconnects.
461                    self.state.set(State::Enumerated)
462                }
463                _ => {}
464            }
465        });
466
467        self.client_ctrl.ctrl_setup(endpoint)
468    }
469
470    /// Handle a Control In transaction
471    fn ctrl_in(&'a self, endpoint: usize) -> hil::usb::CtrlInResult {
472        if self.ctrl_state.get() == CtrlState::GetLineCoding {
473            // Send back the default Line Coding descriptor.
474            self.client_ctrl.prepare_ctrl_in(endpoint, |buf| {
475                descriptors::CdcAcmSetLineCodingData::default().write_to(buf)
476            });
477        }
478
479        self.client_ctrl.ctrl_in(endpoint)
480    }
481
482    /// Handle a Control Out transaction
483    fn ctrl_out(&'a self, endpoint: usize, packet_bytes: u32) -> hil::usb::CtrlOutResult {
484        // Check what state our Ctrl endpoint is in.
485        if self.ctrl_state.get() == CtrlState::SetLineCoding {
486            // We got a Ctrl SET_LINE_CODING setup, now we are getting the data.
487            // We can parse the data we got.
488            descriptors::CdcAcmSetLineCodingData::get(&self.client_ctrl.ctrl_buffer.buf).map(
489                |line_coding| {
490                    // If the device is configuring the baud rate to what we
491                    // expect, we continue with the connecting process.
492                    if line_coding.baud_rate == 115200 {
493                        self.set_connecting_state(true, false);
494                    }
495
496                    // Check if the baud rate we got matches the special flag
497                    // value (1200 baud). If so, we run an optional function
498                    // provided when the CDC stack was configured.
499                    if line_coding.baud_rate == 1200 {
500                        self.host_initiated_function.map(|f| {
501                            f();
502                        });
503                    }
504                },
505            );
506        }
507
508        self.client_ctrl.ctrl_out(endpoint, packet_bytes)
509    }
510
511    fn ctrl_status(&'a self, endpoint: usize) {
512        self.client_ctrl.ctrl_status(endpoint)
513    }
514
515    /// Handle the completion of a Control transfer
516    fn ctrl_status_complete(&'a self, endpoint: usize) {
517        self.ctrl_state.set(CtrlState::Idle);
518
519        // Here we check to see if we just got connected to a CDC client. If so,
520        // we do a delay before transmitting if needed.
521        if let State::Connecting {
522            line_coding,
523            line_state,
524        } = self.state.get()
525        {
526            if line_coding && line_state {
527                self.state.set(State::ConnectingDelay);
528
529                // Wait a 100 ms before sending data.
530                self.timeout_alarm.set_alarm(
531                    self.timeout_alarm.now(),
532                    self.timeout_alarm.ticks_from_ms(100),
533                );
534            }
535        }
536
537        self.client_ctrl.ctrl_status_complete(endpoint)
538    }
539
540    /// Handle a Bulk/Interrupt IN transaction.
541    ///
542    /// This is called when we can send data to the host. It should get called
543    /// when we tell the controller we want to resume the IN endpoint (meaning
544    /// we know we have data to send) and afterwards until we return
545    /// `hil::usb::InResult::Delay` from this function. That means we can use
546    /// this as a callback to mean that the transmission finished by waiting
547    /// until this function is called when we don't have anything left to send.
548    fn packet_in(&'a self, transfer_type: TransferType, endpoint: usize) -> hil::usb::InResult {
549        match transfer_type {
550            TransferType::Bulk => {
551                self.tx_buffer
552                    .take()
553                    .map_or(hil::usb::InResult::Delay, |tx_buf| {
554                        // Check if we have any bytes to send.
555                        let offset = self.tx_offset.get();
556                        let remaining = self.tx_len.get() - offset;
557                        if remaining > 0 {
558                            // We do, so we go ahead and send those.
559
560                            // Get packet that we have shared with the underlying
561                            // USB stack to copy the tx into.
562                            let packet = self.buffer(endpoint);
563
564                            // Calculate how much more we can send.
565                            let to_send = cmp::min(packet.len(), remaining);
566
567                            // Copy from the TX buffer to the outgoing USB packet.
568                            for i in 0..to_send {
569                                packet[i].set(tx_buf[offset + i]);
570                            }
571
572                            // Update our state on how much more there is to send.
573                            self.tx_offset.set(offset + to_send);
574
575                            // Put the TX buffer back so we can keep sending from it.
576                            self.tx_buffer.replace(tx_buf);
577
578                            // Return that we have data to send.
579                            hil::usb::InResult::Packet(to_send)
580                        } else {
581                            // We don't have anything to send, so that means we are
582                            // ok to signal the callback.
583
584                            // Signal the callback and pass back the TX buffer.
585                            self.tx_client.map(move |tx_client| {
586                                tx_client.transmitted_buffer(tx_buf, self.tx_len.get(), Ok(()))
587                            });
588
589                            // Return that we have nothing else to do to the USB
590                            // driver.
591                            hil::usb::InResult::Delay
592                        }
593                    })
594            }
595            TransferType::Control | TransferType::Isochronous | TransferType::Interrupt => {
596                // Nothing to do for CDC ACM.
597                hil::usb::InResult::Delay
598            }
599        }
600    }
601
602    /// Handle a Bulk/Interrupt OUT transaction
603    fn packet_out(
604        &'a self,
605        transfer_type: TransferType,
606        endpoint: usize,
607        packet_bytes: u32,
608    ) -> hil::usb::OutResult {
609        match transfer_type {
610            TransferType::Bulk => {
611                // Start by checking to see if we even care about this RX or
612                // not.
613                self.rx_buffer.take().map(|rx_buf| {
614                    let rx_offset = self.rx_offset.get();
615
616                    // How many more bytes can we store in our RX buffer?
617                    let available_bytes = rx_buf.len() - rx_offset;
618                    let copy_length = cmp::min(packet_bytes as usize, available_bytes);
619
620                    // Do the copy into the RX buffer.
621                    let packet = self.buffer(endpoint);
622                    for i in 0..copy_length {
623                        rx_buf[rx_offset + i] = packet[i].get();
624                    }
625
626                    // Keep track of how many bytes we have received so far.
627                    let total_received_bytes = rx_offset + copy_length;
628
629                    // Update how many bytes we have gotten.
630                    self.rx_offset.set(total_received_bytes);
631
632                    // Check if we have received at least as many bytes as the
633                    // client asked for.
634                    if total_received_bytes >= self.rx_len.get() {
635                        self.rx_client.map(move |client| {
636                            client.received_buffer(
637                                rx_buf,
638                                total_received_bytes,
639                                Ok(()),
640                                uart::Error::None,
641                            );
642                        });
643                    } else {
644                        // Make sure to put the RX buffer back.
645                        self.rx_buffer.replace(rx_buf);
646                    }
647                });
648
649                // No error cases to report to the USB.
650                hil::usb::OutResult::Ok
651            }
652            TransferType::Control | TransferType::Isochronous | TransferType::Interrupt => {
653                // Nothing to do for CDC ACM.
654                hil::usb::OutResult::Ok
655            }
656        }
657    }
658
659    fn packet_transmitted(&'a self, _endpoint: usize) {
660        // Check if more to send.
661        self.tx_buffer.take().map(|tx_buf| {
662            // Check if we have any bytes to send.
663            let remaining = self.tx_len.get() - self.tx_offset.get();
664            if remaining > 0 {
665                // We do, so ask to send again.
666                self.tx_buffer.replace(tx_buf);
667                self.controller().endpoint_resume_in(ENDPOINT_IN_NUM);
668            } else {
669                // We don't have anything to send, so that means we are
670                // ok to signal the callback.
671
672                // Signal the callback and pass back the TX buffer.
673                self.tx_client.map(move |tx_client| {
674                    tx_client.transmitted_buffer(tx_buf, self.tx_len.get(), Ok(()))
675                });
676            }
677        });
678    }
679}
680
681impl<'a, U: hil::usb::UsbController<'a>, A: 'a + Alarm<'a>> uart::Configure for CdcAcm<'a, U, A> {
682    fn configure(&self, _parameters: uart::Parameters) -> Result<(), ErrorCode> {
683        // Since this is not a real UART, we don't need to consider these
684        // parameters.
685        Ok(())
686    }
687}
688
689impl<'a, U: hil::usb::UsbController<'a>, A: 'a + Alarm<'a>> uart::Transmit<'a>
690    for CdcAcm<'a, U, A>
691{
692    fn set_transmit_client(&self, client: &'a dyn uart::TransmitClient) {
693        self.tx_client.set(client);
694    }
695
696    fn transmit_buffer(
697        &self,
698        tx_buffer: &'static mut [u8],
699        tx_len: usize,
700    ) -> Result<(), (ErrorCode, &'static mut [u8])> {
701        if self.tx_buffer.is_some() {
702            // We are already handling a transmission, we cannot queue another
703            // request.
704            Err((ErrorCode::BUSY, tx_buffer))
705        } else if tx_len > tx_buffer.len() {
706            // Can't send more bytes than will fit in the buffer.
707            Err((ErrorCode::SIZE, tx_buffer))
708        } else {
709            // Ok, we can handle this transmission. Initialize all of our state
710            // for our TX state machine.
711            self.tx_len.set(tx_len);
712            self.tx_offset.set(0);
713            self.tx_buffer.replace(tx_buffer);
714
715            // Don't try to send if there is no CDC client connected.
716            if self.state.get() == State::Connected {
717                // Then signal to the lower layer that we are ready to do a TX
718                // by putting data in the IN endpoint.
719                self.controller().endpoint_resume_in(ENDPOINT_IN_NUM);
720                Ok(())
721            } else if self.boot_period.get() {
722                // indicate success because we will try to send it once a host connects
723                Ok(())
724            } else {
725                // indicate success, but we will not actually queue this message -- just schedule
726                // a deferred callback to return the buffer immediately.
727                self.deferred_call_pending_droptx.set(true);
728                self.deferred_call.set();
729                Ok(())
730            }
731        }
732    }
733
734    fn transmit_abort(&self) -> Result<(), ErrorCode> {
735        Err(ErrorCode::FAIL)
736    }
737
738    fn transmit_word(&self, _word: u32) -> Result<(), ErrorCode> {
739        Err(ErrorCode::FAIL)
740    }
741}
742
743impl<'a, U: hil::usb::UsbController<'a>, A: 'a + Alarm<'a>> uart::Receive<'a> for CdcAcm<'a, U, A> {
744    fn set_receive_client(&self, client: &'a dyn uart::ReceiveClient) {
745        self.rx_client.set(client);
746    }
747
748    fn receive_buffer(
749        &self,
750        rx_buffer: &'static mut [u8],
751        rx_len: usize,
752    ) -> Result<(), (ErrorCode, &'static mut [u8])> {
753        if self.rx_buffer.is_some() {
754            Err((ErrorCode::BUSY, rx_buffer))
755        } else if rx_len > rx_buffer.len() {
756            Err((ErrorCode::SIZE, rx_buffer))
757        } else {
758            self.rx_buffer.replace(rx_buffer);
759            self.rx_offset.set(0);
760            self.rx_len.set(rx_len);
761
762            Ok(())
763        }
764    }
765
766    fn receive_abort(&self) -> Result<(), ErrorCode> {
767        if self.rx_buffer.is_none() {
768            // If we have nothing pending then aborting is very easy.
769            Ok(())
770        } else {
771            // If we do have a receive pending then we need to start a deferred
772            // call to set the callback and return `BUSY`.
773            self.deferred_call_pending_abortrx.set(true);
774            self.deferred_call.set();
775            Err(ErrorCode::BUSY)
776        }
777    }
778
779    fn receive_word(&self) -> Result<(), ErrorCode> {
780        Err(ErrorCode::FAIL)
781    }
782}
783
784impl<'a, U: hil::usb::UsbController<'a>, A: 'a + Alarm<'a>> AlarmClient for CdcAcm<'a, U, A> {
785    fn alarm(&self) {
786        self.boot_period.set(false);
787
788        // This alarm is used in two cases. The main is when we first start to
789        // delay outgoing messages until a host has a chance to connect. The
790        // second is to delay after a host does connect to help ensure messages
791        // actually get printed. If this timer goes off, then either no host
792        // connected, and we want to start dropping messages, or something did
793        // connect and we just executed the delay.
794        if self.state.get() == State::ConnectingDelay {
795            self.state.set(State::Connected);
796            if self.tx_buffer.is_some() {
797                self.controller().endpoint_resume_in(ENDPOINT_IN_NUM);
798            }
799        } else {
800            // no client has connected, but we do not want to block indefinitely, so go ahead
801            // and deliver a callback.
802            self.indicate_tx_success();
803        }
804    }
805}
806
807impl<'a, U: hil::usb::UsbController<'a>, A: 'a + Alarm<'a>> DeferredCallClient
808    for CdcAcm<'a, U, A>
809{
810    fn handle_deferred_call(&self) {
811        if self.deferred_call_pending_droptx.replace(false) {
812            self.indicate_tx_success()
813        }
814
815        if self.deferred_call_pending_abortrx.replace(false) {
816            // Signal the RX callback with CANCEL error.
817            self.rx_buffer.take().map(|rx_buf| {
818                let rx_offset = self.rx_offset.get();
819
820                // The total number of bytes we have received so far.
821                let total_received_bytes = rx_offset;
822
823                self.rx_client.map(move |client| {
824                    client.received_buffer(
825                        rx_buf,
826                        total_received_bytes,
827                        Err(ErrorCode::CANCEL),
828                        uart::Error::None,
829                    );
830                });
831            });
832        }
833    }
834
835    fn register(&'static self) {
836        self.deferred_call.register(self);
837    }
838}