From ecb5e513d1d93cfd3f34fd3225fb7b988c8dde05 Mon Sep 17 00:00:00 2001 From: doryan Date: Sat, 9 Nov 2024 16:46:12 +0400 Subject: [PATCH] feat(alloc_ep): refactor + add comments --- src/types/usb_device.rs | 29 +++++++++++++++++++++++------ 1 file changed, 23 insertions(+), 6 deletions(-) diff --git a/src/types/usb_device.rs b/src/types/usb_device.rs index 241a888..cf69629 100644 --- a/src/types/usb_device.rs +++ b/src/types/usb_device.rs @@ -146,41 +146,56 @@ impl UsbBus for UsbDevice { ep_type: EndpointType, max_packet_size: u16, _interval: u8, - ) -> Result { + ) -> UsbResult { + // Handle first endpoint. // if ep_addr == Some(EndpointAddress::from_parts(0, UsbDirection::In)) { return Ok(ep_addr.unwrap()); } let address = match ep_addr { + // If current endpoint doesn't allocated, assign ep_addr to variable. // Some(ep_addr) if !self.ep_table[ep_addr.index()].is_allocated => ep_addr, - Some(_) => unreachable!(), - None => { + + // If ep_aadr not provided, or current endpoint is allocated, try to find next free endpoint, otherwise return UsbError. // + None | Some(_) => { let endpoint = self .ep_table .iter() .enumerate() .skip(1) - .find(|(i, &ep)| !ep.is_allocated && max_packet_size <= ENDPOINTS_ALLOC_LAYOUT[*i]) + .find(|(i, &ep)| { + !ep.is_allocated && max_packet_size <= ENDPOINTS_ALLOC_LAYOUT[*i] + }) .ok_or(UsbError::EndpointMemoryOverflow)?; EndpointAddress::from_parts(endpoint.0, ep_dir) } }; + // Select endpoint info by address index. // + let target_endpoint = &mut self.ep_table[address.index()]; + // Endpoint allocation marker. // + if DPRAM_SIZE - self.dpram_already_used <= max_packet_size || max_packet_size >= 512 { Err(UsbError::EndpointMemoryOverflow) } else { + + // Get power of two number of endpoint size. // + let max_packet_size = max(8, max_packet_size.next_power_of_two()); + // Set endpoint parameters. // + target_endpoint.set_size(max_packet_size); target_endpoint.set_dir(ep_dir); target_endpoint.set_type(ep_type); - target_endpoint.is_allocated = true; - self.dpram_already_used = max_packet_size; + // Add used dpram memory. // + + self.dpram_already_used += max_packet_size; Ok(address) } @@ -231,8 +246,10 @@ impl UsbBus for UsbDevice { fn force_reset(&self) -> usb_device::Result<()> { free(|cs| { let usb = self.usb.borrow(cs); + usb.usbcon.modify(|_, w| w.usbe().clear_bit()); usb.usbcon.modify(|_, w| w.usbe().set_bit()); + Ok(()) }) }