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
use usb_device::{Result, UsbError, UsbDirection};
use usb_device::endpoint::EndpointAddress;
use crate::endpoint_memory::{EndpointBuffer, EndpointBufferState};
use crate::ral::{read_reg, write_reg, modify_reg, endpoint_in, endpoint_out, endpoint0_out};
use crate::target::{fifo_write, UsbRegisters};
use crate::target::interrupt::{self, CriticalSection, Mutex};
use core::ops::{Deref, DerefMut};
use core::cell::RefCell;
use crate::transition::EndpointDescriptor;
use crate::UsbPeripheral;

pub fn set_stalled(usb: UsbRegisters, address: EndpointAddress, stalled: bool) {
    interrupt::free(|_| {
        match address.direction() {
            UsbDirection::Out => {
                let ep = usb.endpoint_out(address.index() as usize);
                modify_reg!(endpoint_out, ep, DOEPCTL, STALL: stalled as u32);
            },
            UsbDirection::In => {
                let ep = usb.endpoint_in(address.index() as usize);
                modify_reg!(endpoint_in, ep, DIEPCTL, STALL: stalled as u32);
            },
        }
    })
}

pub fn is_stalled(usb: UsbRegisters, address: EndpointAddress) -> bool {
    let stall = match address.direction() {
        UsbDirection::Out => {
            let ep = usb.endpoint_out(address.index());
            read_reg!(endpoint_out, ep, DOEPCTL, STALL)
        },
        UsbDirection::In => {
            let ep = usb.endpoint_in(address.index());
            read_reg!(endpoint_in, ep, DIEPCTL, STALL)
        },
    };
    stall != 0
}

/// Arbitrates access to the endpoint-specific registers and packet buffer memory.
pub struct Endpoint {
    descriptor: EndpointDescriptor,
    usb: UsbRegisters,
}

impl Endpoint {
    pub fn new<USB: UsbPeripheral>(descriptor: EndpointDescriptor) -> Endpoint {
        Endpoint {
            descriptor,
            usb: UsbRegisters::new::<USB>()
        }
    }

    pub fn address(&self) -> EndpointAddress {
        self.descriptor.address
    }

    #[inline(always)]
    fn index(&self) -> u8 {
        self.descriptor.address.index() as u8
    }
}


pub struct EndpointIn {
    common: Endpoint,
}

impl EndpointIn {
    pub fn new<USB: UsbPeripheral>(descriptor: EndpointDescriptor) -> EndpointIn {
        EndpointIn {
            common: Endpoint::new::<USB>(descriptor),
        }
    }

    pub fn configure(&self, _cs: &CriticalSection) {
        if self.index() == 0 {
            let mpsiz = match self.descriptor.max_packet_size {
                8 => 0b11,
                16 => 0b10,
                32 => 0b01,
                64 => 0b00,
                other => panic!("Unsupported EP0 size: {}", other),
            };

            let regs = self.usb.endpoint_in(self.index() as usize);
            write_reg!(endpoint_in, regs, DIEPCTL, MPSIZ: mpsiz as u32, SNAK: 1);
            write_reg!(endpoint_in, regs, DIEPTSIZ, PKTCNT: 0, XFRSIZ: self.descriptor.max_packet_size as u32);
        } else {
            let regs = self.usb.endpoint_in(self.index() as usize);
            write_reg!(endpoint_in, regs, DIEPCTL,
                SNAK: 1,
                USBAEP: 1,
                EPTYP: self.descriptor.ep_type as u32,
                SD0PID_SEVNFRM: 1,
                TXFNUM: self.index() as u32,
                MPSIZ: self.descriptor.max_packet_size as u32
            );
        }
    }

    pub fn deconfigure(&self, _cs: &CriticalSection) {
        let regs = self.usb.endpoint_in(self.index() as usize);

        // deactivating endpoint
        modify_reg!(endpoint_in, regs, DIEPCTL, USBAEP: 0);

        // TODO: flushing FIFO

        // disabling endpoint
        if read_reg!(endpoint_in, regs, DIEPCTL, EPENA) != 0 && self.index() != 0 {
            modify_reg!(endpoint_in, regs, DIEPCTL, EPDIS: 1)
        }

        // clean EP interrupts
        write_reg!(endpoint_in, regs, DIEPINT, 0xff);

        // TODO: deconfiguring TX FIFO
    }

    pub fn write(&self, buf: &[u8]) -> Result<()> {
        let ep = self.usb.endpoint_in(self.index() as usize);
        if self.index() != 0 && read_reg!(endpoint_in, ep, DIEPCTL, EPENA) != 0{
            return Err(UsbError::WouldBlock);
        }

        if buf.len() > self.descriptor.max_packet_size as usize {
            return Err(UsbError::BufferOverflow);
        }

        if !buf.is_empty() {
            // Check for FIFO free space
            let size_words = (buf.len() + 3) / 4;
            if size_words > read_reg!(endpoint_in, ep, DTXFSTS, INEPTFSAV) as usize {
                return Err(UsbError::WouldBlock);
            }
        }

        #[cfg(feature = "fs")]
        write_reg!(endpoint_in, ep, DIEPTSIZ, PKTCNT: 1, XFRSIZ: buf.len() as u32);
        #[cfg(feature = "hs")]
        write_reg!(endpoint_in, ep, DIEPTSIZ, MCNT: 1, PKTCNT: 1, XFRSIZ: buf.len() as u32);

        modify_reg!(endpoint_in, ep, DIEPCTL, CNAK: 1, EPENA: 1);

        fifo_write(self.usb, self.index(), buf);

        Ok(())
    }
}

pub struct EndpointOut {
    common: Endpoint,
    pub(crate) buffer: Mutex<RefCell<EndpointBuffer>>,
}

impl EndpointOut {
    pub fn new<USB: UsbPeripheral>(descriptor: EndpointDescriptor, buffer: EndpointBuffer) -> EndpointOut {
        EndpointOut {
            common: Endpoint::new::<USB>(descriptor),
            buffer: Mutex::new(RefCell::new(buffer)),
        }
    }

    pub fn configure(&self, _cs: &CriticalSection) {
        if self.index() == 0 {
            let mpsiz = match self.descriptor.max_packet_size {
                8 => 0b11,
                16 => 0b10,
                32 => 0b01,
                64 => 0b00,
                other => panic!("Unsupported EP0 size: {}", other),
            };

            let regs = self.usb.endpoint0_out();
            write_reg!(endpoint0_out, regs, DOEPTSIZ0, STUPCNT: 1, PKTCNT: 1, XFRSIZ: self.descriptor.max_packet_size as u32);
            modify_reg!(endpoint0_out, regs, DOEPCTL0, MPSIZ: mpsiz as u32, EPENA: 1, CNAK: 1);
        } else {
            let regs = self.usb.endpoint_out(self.index() as usize);
            write_reg!(endpoint_out, regs, DOEPCTL,
                SD0PID_SEVNFRM: 1,
                CNAK: 1,
                EPENA: 1,
                USBAEP: 1,
                EPTYP: self.descriptor.ep_type as u32,
                MPSIZ: self.descriptor.max_packet_size as u32
            );
        }
    }

    pub fn deconfigure(&self, _cs: &CriticalSection) {
        let regs = self.usb.endpoint_out(self.index() as usize);

        // deactivating endpoint
        modify_reg!(endpoint_out, regs, DOEPCTL, USBAEP: 0);

        // disabling endpoint
        if read_reg!(endpoint_out, regs, DOEPCTL, EPENA) != 0 && self.index() != 0 {
            modify_reg!(endpoint_out, regs, DOEPCTL, EPDIS: 1)
        }

        // clean EP interrupts
        write_reg!(endpoint_out, regs, DOEPINT, 0xff);
    }

    pub fn read(&self, buf: &mut [u8]) -> Result<usize> {
        interrupt::free(|cs| {
            self.buffer.borrow(cs).borrow_mut().read_packet(buf)
        })
    }

    pub fn buffer_state(&self) -> EndpointBufferState {
        interrupt::free(|cs| {
            self.buffer.borrow(cs).borrow().state()
        })
    }
}


impl Deref for EndpointIn {
    type Target = Endpoint;

    fn deref(&self) -> &Self::Target {
        &self.common
    }
}

impl DerefMut for EndpointIn {
    fn deref_mut(&mut self) -> &mut Self::Target {
        &mut self.common
    }
}

impl Deref for EndpointOut {
    type Target = Endpoint;

    fn deref(&self) -> &Self::Target {
        &self.common
    }
}

impl DerefMut for EndpointOut {
    fn deref_mut(&mut self) -> &mut Self::Target {
        &mut self.common
    }
}