Make common_arm to hardware abstraction layer.

This commit is contained in:
dxl authored and Philippe Teuwen committed 2026-08-19 15:32:39 +02:00
1 parent 51d0ff260a
commit 36f1c7e44c
61 files changed
+8050 -1670

No files matched your search

+41
View File
@@ -0,0 +1,41 @@
//-----------------------------------------------------------------------------
// Copyright (C) Proxmark3 contributors. See AUTHORS.md for details.
//
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
// See LICENSE.txt for the text of the license.
//-----------------------------------------------------------------------------
// 20250814: Abstract definition, without any platform related information.
//-----------------------------------------------------------------------------
#ifndef USB_CDC_H_
#define USB_CDC_H_
#include "common.h"
void usb_disable(void);
void usb_enable(void);
bool usb_check(void);
bool usb_poll(void);
uint16_t usb_available_length(void);
bool usb_poll_validate_length(void);
uint32_t usb_read(uint8_t *data, size_t len);
int usb_write(const uint8_t *data, size_t len);
int async_usb_write_start(void);
void async_usb_write_pushByte(uint8_t data);
bool async_usb_write_requestWrite(void);
int async_usb_write_stop(void);
void usb_update_serial(uint64_t newSerialNumber);
void usb_get_ep_size(uint32_t *epCtl, uint32_t *epIn, uint32_t *epOut);
#endif // USB_CDC_H_
+636
View File
@@ -0,0 +1,636 @@
#include "pm3_cmd.h"
#include "ticks_apis.h"
#include "usb_cdc_apis.h"
#include "usb_read_ng.h"
#include "usb_cdc_desc.h"
#include "at32f435_437_crm.h"
#include "at32f435_437_acc.h"
#include "at32f435_437_gpio.h"
#include "at32f435_437_misc.h"
#include "usb_conf.h"
#include "usb_core.h"
#include "usbd_int.h"
#include "cdc_class.h"
static otg_core_type otg_core_struct;
static usbd_core_type *udev = &(otg_core_struct.dev);
static usbd_desc_t vp_desc;
/**
* @brief get device descriptor
* @retval usbd_desc
*/
static usbd_desc_t *get_device_descriptor(void) {
// Must be static !!!!!!
static usbd_desc_t device_descriptor = {
.length = sizeof(devDescriptor),
.descriptor = (uint8_t *) devDescriptor
};
return &device_descriptor;
}
/**
* @brief get device qualifier
* @retval usbd_desc
*/
static usbd_desc_t *get_device_qualifier(void) {
return NULL;
}
/**
* @brief get config descriptor
* @retval usbd_desc
*/
static usbd_desc_t *get_device_configuration(void) {
// Must be static !!!!!!
static usbd_desc_t config_descriptor = {
.length = sizeof(cfgDescriptor),
.descriptor = (uint8_t *) cfgDescriptor
};
return &config_descriptor;
}
/**
* @brief get other speed descriptor
* @retval usbd_desc
*/
static usbd_desc_t *get_device_other_speed(void) {
return NULL;
}
/**
* @brief get lang id descriptor
* @retval usbd_desc
*/
static usbd_desc_t *get_device_lang_id(void) {
// Must be static !!!!!!
static usbd_desc_t langid_descriptor = {
.length = sizeof(StrLanguageCodes),
.descriptor = (uint8_t *) StrLanguageCodes
};
return &langid_descriptor;
}
/**
* @brief get manufacturer descriptor
* @retval usbd_desc
*/
static usbd_desc_t *get_device_manufacturer_string(void) {
vp_desc.length = StrManufacturer[0];
vp_desc.descriptor = (uint8_t *) StrManufacturer;
return &vp_desc;
}
/**
* @brief get product descriptor
* @retval usbd_desc
*/
static usbd_desc_t *get_device_product_string(void) {
vp_desc.length = StrProduct[0];
vp_desc.descriptor = (uint8_t *) StrProduct;
return &vp_desc;
}
/**
* @brief get serial descriptor
* @retval usbd_desc
*/
static usbd_desc_t *get_device_serial_string(void) {
// Must be static !!!!!!
static usbd_desc_t serial_descriptor = {
.length = sizeof(StrSerialNumber),
.descriptor = (uint8_t *) StrSerialNumber
};
return &serial_descriptor;
}
/**
* @brief get interface descriptor
* @retval usbd_desc
*/
static usbd_desc_t *get_device_interface_string(void) {
return NULL;
}
/**
* @brief get device config descriptor
* @retval usbd_desc
*/
static usbd_desc_t *get_device_config_string(void) {
return NULL;
}
/**
* @brief get device config descriptor
* @retval usbd_desc
*/
static usbd_desc_t *get_winusb_os_string(void) {
vp_desc.length = StrMS_OSDescriptor[0];
vp_desc.descriptor = (uint8_t *) StrMS_OSDescriptor;
return &vp_desc;
}
/**
* @brief device descriptor handler structure
*/
static usbd_desc_handler cdc_desc_handler =
{
.get_device_descriptor = get_device_descriptor,
.get_device_qualifier = get_device_qualifier,
.get_device_configuration = get_device_configuration,
.get_device_other_speed = get_device_other_speed,
.get_device_lang_id = get_device_lang_id,
// ---
.get_device_manufacturer_string = get_device_manufacturer_string,
.get_device_product_string = get_device_product_string,
.get_device_serial_string = get_device_serial_string,
.get_device_interface_string = get_device_interface_string,
.get_device_config_string = get_device_config_string,
// ---
.get_device_winusb_os_string = get_winusb_os_string,
.get_device_winusb_os_feature = NULL,
.get_device_winusb_os_property = NULL
};
/**
* @brief usb 48M clock select
* @param clk_s:USB_CLK_HICK, USB_CLK_HEXT
* @retval none
*/
static void usb_clock48m_select(usb_clk48_s clk_s) {
if (clk_s == USB_CLK_HICK) {
/* UNUSED!!!
crm_usb_clock_source_select(CRM_USB_CLOCK_SOURCE_HICK);
// enable the acc calibration ready interrupt
crm_periph_clock_enable(CRM_ACC_PERIPH_CLOCK, TRUE);
// update the c1\c2\c3 value
acc_write_c1(7980);
acc_write_c2(8000);
acc_write_c3(8020);
#if (USB_ID == 0)
acc_sof_select(ACC_SOF_OTG1);
#else
acc_sof_select(ACC_SOF_OTG2);
#endif
// open acc calibration
acc_calibration_mode_enable(ACC_CAL_HICKTRIM, TRUE);
*/
} else {
switch (system_core_clock) {
/* 48MHz */
case 48000000:
crm_usb_clock_div_set(CRM_USB_DIV_1);
break;
/* 72MHz */
case 72000000:
crm_usb_clock_div_set(CRM_USB_DIV_1_5);
break;
/* 96MHz */
case 96000000:
crm_usb_clock_div_set(CRM_USB_DIV_2);
break;
/* 120MHz */
case 120000000:
crm_usb_clock_div_set(CRM_USB_DIV_2_5);
break;
/* 144MHz */
case 144000000:
crm_usb_clock_div_set(CRM_USB_DIV_3);
break;
/* 168MHz */
case 168000000:
crm_usb_clock_div_set(CRM_USB_DIV_3_5);
break;
/* 192MHz */
case 192000000:
crm_usb_clock_div_set(CRM_USB_DIV_4);
break;
/* 216MHz */
case 216000000:
crm_usb_clock_div_set(CRM_USB_DIV_4_5);
break;
/* 240MHz */
case 240000000:
crm_usb_clock_div_set(CRM_USB_DIV_5);
break;
/* 264MHz */
case 264000000:
crm_usb_clock_div_set(CRM_USB_DIV_5_5);
break;
/* 288MHz */
case 288000000:
crm_usb_clock_div_set(CRM_USB_DIV_6);
break;
default:
break;
}
}
}
/**
* @brief this function config gpio.
* @retval none
*/
static void usb_gpio_config(void) {
gpio_init_type gpio_init_struct;
crm_periph_clock_enable(OTG_PIN_GPIO_CLOCK, TRUE);
gpio_default_para_init(&gpio_init_struct);
gpio_init_struct.gpio_drive_strength = GPIO_DRIVE_STRENGTH_STRONGER;
gpio_init_struct.gpio_out_type = GPIO_OUTPUT_PUSH_PULL;
gpio_init_struct.gpio_mode = GPIO_MODE_MUX;
gpio_init_struct.gpio_pull = GPIO_PULL_NONE;
/* dp and dm */
gpio_init_struct.gpio_pins = OTG_PIN_DP | OTG_PIN_DM;
gpio_init(OTG_PIN_GPIO, &gpio_init_struct);
gpio_pin_mux_config(OTG_PIN_GPIO, OTG_PIN_DP_SOURCE, OTG_PIN_MUX);
gpio_pin_mux_config(OTG_PIN_GPIO, OTG_PIN_DM_SOURCE, OTG_PIN_MUX);
#ifdef USB_SOF_OUTPUT_ENABLE
crm_periph_clock_enable(OTG_PIN_SOF_GPIO_CLOCK, TRUE);
gpio_init_struct.gpio_pins = OTG_PIN_SOF;
gpio_init(OTG_PIN_SOF_GPIO, &gpio_init_struct);
gpio_pin_mux_config(OTG_PIN_SOF_GPIO, OTG_PIN_SOF_SOURCE, OTG_PIN_MUX);
#endif
/* otgfs use vbus pin */
#ifndef USB_VBUS_IGNORE
gpio_init_struct.gpio_pins = OTG_PIN_VBUS;
gpio_init_struct.gpio_pull = GPIO_PULL_DOWN;
gpio_pin_mux_config(OTG_PIN_GPIO, OTG_PIN_VBUS_SOURCE, OTG_PIN_MUX);
gpio_init(OTG_PIN_GPIO, &gpio_init_struct);
#endif
}
// predefine, resolve compiler warning.
void OTG_IRQ_HANDLER(void);
/**
* @brief this function handles otgfs interrupt.
* @retval none
*/
void OTG_IRQ_HANDLER(void) {
usbd_irq_handler(&otg_core_struct);
}
/**
* @brief usb delay millisecond function.
* @param ms: number of millisecond delay
* @retval none
*/
void usb_delay_ms(uint32_t ms) {
// Did not use !!!! ANY delay if bootrom unsupported !!!! see: ticks.h -> AS_BOOTROM macro
SpinDelayUs(ms * 1000);
}
// unused, don't need to implement.
// /**
// * @brief usb delay microsecond function.
// * @param us: number of microsecond delay
// * @retval none
// */
// void usb_delay_us(uint32_t us) {
// delay_us(us);
// }
#ifndef AS_BOOTROM
static uint8_t usb_read_ng_buffer[64] = {0};
static uint8_t usb_read_ng_fifo_pos = 0;
// Implemented for read_ng
static bool usb_read_ng_link_ready(void) {
return usb_check(); // reuse 'usb_check()'
}
// Implemented for read_ng
static bool usb_read_ng_data_ready(void) {
cdc_struct_type *pcdc = (cdc_struct_type *) (udev->class_handler->pdata);
return pcdc->g_rx_completed;
}
// Implemented for read_ng
static uint16_t usb_read_ng_data_available(void) {
return usb_available_length();
}
// Implemented for read_ng
static uint8_t usb_read_ng_data_read(void) {
cdc_struct_type *pcdc = (cdc_struct_type *) (udev->class_handler->pdata);
return pcdc->g_rx_buff[usb_read_ng_fifo_pos++];
}
// Implemented for read_ng
static void usb_read_ng_clear(void) {
cdc_struct_type *pcdc = (cdc_struct_type *) (udev->class_handler->pdata);
// When receiving data from USB device is completed, the flag bit of receiving completion must be cleared,
// otherwise, it will enter the endless cycle of receiving completion and may repeatedly execute an instruction.
pcdc->g_rx_completed = 0;
// usb_read_ng_data_read() will increment position when read, so we need reset on read finished.
// if reset forgot, usb_read_ng_data_read() will read wrong data(cause by overflow).
usb_read_ng_fifo_pos = 0;
// receive enable
usbd_ept_recv(udev, USBD_CDC_BULK_OUT_EPT, pcdc->g_rx_buff, USBD_CDC_OUT_MAXPACKET_SIZE);
}
// Instance for 'read_ng' apis
static const usb_read_ng_config_t g_usb_read_ng_config = {
.is_link_ready = usb_read_ng_link_ready,
.is_data_ready = usb_read_ng_data_ready,
.get_byte_count = usb_read_ng_data_available,
.read_fifo = usb_read_ng_data_read,
.clear_ready = usb_read_ng_clear,
.buffer = usb_read_ng_buffer,
.buffer_size = sizeof(usb_read_ng_buffer),
.timeout = 0x1FFF
};
#endif
/**
* This function Activates the USB device
*/
void usb_enable(void) {
usb_gpio_config();
crm_periph_clock_enable(OTG_CLOCK, TRUE); // enable otgfs clock
usb_clock48m_select(USB_CLK_HEXT); // select usb 48m clcok source
nvic_irq_enable(OTG_IRQ, 0, 0); // enable otgfs irq
usbd_init(&otg_core_struct, USB_FULL_SPEED_CORE_ID,USB_ID, &cdc_class_handler, &cdc_desc_handler); // init usb
#ifndef AS_BOOTROM
usb_read_ng_init(&g_usb_read_ng_config);
#endif
}
/**
* This function deactivates the USB device
*/
void usb_disable(void) {
nvic_irq_disable(OTG_IRQ); // disable otgfs irq
NVIC_ClearPendingIRQ(OTG_IRQ); // clear otgfs irq if pedding
crm_periph_clock_enable(OTG_CLOCK, FALSE); // disable otgfs clock
}
/**
* Test if the device is configured and handle enumeration
* @return true if configured, otherwise fasle.
*/
bool usb_check(void) {
return udev->conn_state == USB_CONN_STATE_CONFIGURED;
}
/**
* Test if the device link ok and data received.
* @return true if link ok and data received, otherwise fasle.
*/
bool usb_poll(void) {
if (usb_check() == false) {
return false;
}
// g_rx_completed will set to 1 when irq event: USB_OTG_DOEPINT_XFERC_FLAG
cdc_struct_type *pcdc = (cdc_struct_type *) (udev->class_handler->pdata);
return pcdc->g_rx_completed;
}
/**
* Get data received length of out endpoint.
* @return data length, if no data received, return 0.
*/
uint16_t usb_available_length(void) {
cdc_struct_type *pcdc = (cdc_struct_type *) (udev->class_handler->pdata);
// Only when g_rx_completed is set, the g_rxlen is valid, otherwise, it may be 0 or invalid.
if (pcdc->g_rx_completed) {
return pcdc->g_rxlen;
}
return 0;
}
/**
* Test if the device link ok and data received.
* note: this function will check data length > 0
* @return
*/
bool usb_poll_validate_length(void) {
if (usb_poll() == false) {
return false;
}
return usb_available_length() > 0;
}
/**
* Read available data from Endpoint 1 OUT (host to device, blocking read.)
* @param data the data buffer read into.
* @param len the max length of data.
* @return
*/
uint32_t usb_read(uint8_t *data, size_t len) {
if (len == 0) return 0; // invalid length
uint16_t nbBytesRcv = 0;
uint16_t time_out = 0;
uint16_t packetSize = 0;
while (len) {
if (usb_check() == false) {
break;
}
// example: 150bytes receive from HOST
// OUT endpoint buffer size is 64.
// so, usb controller will split to 3 packet for send.
// 1. 64 -> packetSize(64) = usb_vcp_get_rxdata(udev, data + nbBytesRcv(0), len(150));
// 2. 64 -> packetSize(64) = usb_vcp_get_rxdata(udev, data + nbBytesRcv(64), len(86));
// 3. 22 -> packetSize(22) = usb_vcp_get_rxdata(udev, data + nbBytesRcv(128), len(22));
// after the third time received, the len -= 22 get 0. loop end.
packetSize = usb_vcp_get_rxdata(udev, data + nbBytesRcv, len);
if (packetSize != 0) {
len -= packetSize;
nbBytesRcv += packetSize;
}
// simple timeout.
if (time_out++ == 0x1FFF) {
break;
}
}
return nbBytesRcv;
}
/**
* Send through endpoint 2 (device to host, blocking write.)
* @param data the data will send
* @param len the data length
* @return result value
*/
int usb_write(const uint8_t *data, const size_t len) {
if (len == 0) {
return PM3_EINVARG;
}
if (usb_check() == false) {
return PM3_EIO;
}
// 'usb_vcp_send_data()' will auto split packet.
if (usb_vcp_send_data(udev, (uint8_t *) data, len) != SUCCESS) {
return PM3_EIO;
}
// wait for send complete
cdc_struct_type *pcdc = (cdc_struct_type *) (udev->class_handler->pdata);
while (pcdc->g_tx_completed != 1) {
if (usb_check() == false) {
return PM3_EIO;
}
// working for send to HOST...
// Have a cup of tea?
}
return PM3_SUCCESS;
}
// --------------------------------- ASYNC WRITE APIS ---------------------------------
static uint8_t async_write_buffer[2][USBD_CDC_IN_MAXPACKET_SIZE]; // double buffer, like at91 double bank.
static uint8_t async_write_buf_select = 0;
static uint8_t async_write_index = 0;
/**
* Check is write data finished.
* @return
*/
static uint8_t is_write_completed(otg_eptin_type *ept_in) {
if (ept_in->dieptsiz_bit.xfersize != 0) {
return FALSE;
}
return TRUE;
}
/**
* Start the buffer write, wait for last send finished and flush fifo.
* @return error status
*/
int async_usb_write_start(void) {
otg_eptin_type *ept_in = USB_INEPT(udev->usb_reg, (USBD_CDC_BULK_IN_EPT & 0x7F));
otg_device_type *dev = OTG_DEVICE(udev->usb_reg);
// check usb state
if (!usb_check()) return PM3_EIO;
// wait for tx end if working...
while (!is_write_completed(ept_in)) if (!usb_check()) return PM3_EIO;
// disable fifo empty irq.
dev->diepempmsk &= ~(1 << (USBD_CDC_BULK_IN_EPT & 0x7F));
// check fifo status before async write.
usbd_ept_in_check_fifo(udev, USBD_CDC_BULK_IN_EPT & 0x7F);
// reset flag
async_write_buf_select = 0;
async_write_index = 0;
// AT32 和 CH32 的USB功能区别挺大,注意不要陷入惯性思维的陷阱。
// 对于AT32,需要先设置端点控制寄存器中的传输长度和包数目位,并使能端点来传输数据。最后然后再去写FIFO
// 对于CH32,需要先写入BUFF,然后再设置传输长度,最后再使能发送和ACK。
return PM3_SUCCESS;
}
/**
* Push 1 byte data to usb fifo, but no send start.
* @param b the byte will push to usb fifo
*/
void async_usb_write_pushByte(uint8_t b) {
if (async_write_index >= USBD_CDC_IN_MAXPACKET_SIZE) {
return; // !!! WARN !!! Can't to here, will memory overflow.
}
async_write_buffer[async_write_buf_select][async_write_index] = b;
async_write_index++;
}
/**
* Flush the send buffer, next IN event will trans to HOST
*/
bool async_usb_write_requestWrite(void) {
// get reg
otg_eptin_type *ept_in = USB_INEPT(udev->usb_reg, (USBD_CDC_BULK_IN_EPT & 0x7F));
// check last transmit is finish? cond: trans remain length not 0 or fifo have data.
if (!is_write_completed(ept_in)) return FALSE;
// set transfer length and packet count.
ept_in->dieptsiz_bit.xfersize = async_write_index;
ept_in->dieptsiz_bit.pktcnt = 1;
// dieptsiz_bit register must set before 'eptena' set. it will lock after 'eptena' = TRUE
// clear endpoint nak
ept_in->diepctl_bit.cnak = TRUE;
// IN endpoint enable
ept_in->diepctl_bit.eptena = TRUE;
// write data to fifo.
usb_write_packet(
udev->usb_reg,
async_write_buffer[async_write_buf_select],
USBD_CDC_BULK_IN_EPT & 0x7F,
async_write_index
);
async_write_buf_select = ~async_write_buf_select; // after data write, we can change buffer, 0 or 1
async_write_index = 0; // don't forget reset write index, next write will write to other buffer and from 0 start.
return TRUE;
}
/**
* Stop send and wait finish.
* @return SUCCESS if send stop success, otherwise ERROR
*/
int async_usb_write_stop(void) {
otg_eptin_type *ept_in = USB_INEPT(udev->usb_reg, (USBD_CDC_BULK_IN_EPT & 0x7F));
// Wait for the end of transfer
while (!is_write_completed(ept_in)) if (!usb_check()) return PM3_EIO;
// still have data on local buffer, we need send before write stop.
if (async_write_index != 0) {
if (!async_usb_write_requestWrite()) {
return PM3_EIO;
}
}
// Wait for the end of fifo flush transfer.
while (!is_write_completed(ept_in)) if (!usb_check()) return PM3_EIO;
return PM3_SUCCESS;
}
/**
* Get endpoint buffer size.
*/
void usb_get_ep_size(uint32_t *epCtl, uint32_t *epIn, uint32_t *epOut) {
if (epCtl) *epCtl = USBD_CDC_CMD_MAXPACKET_SIZE;
if (epIn) *epIn = USBD_CDC_IN_MAXPACKET_SIZE;
if (epOut) *epOut = USBD_CDC_OUT_MAXPACKET_SIZE;
}
+898
View File
@@ -0,0 +1,898 @@
//-----------------------------------------------------------------------------
// Copyright (C) Proxmark3 contributors. See AUTHORS.md for details.
//
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
// See LICENSE.txt for the text of the license.
//-----------------------------------------------------------------------------
// at91sam7s USB CDC device implementation
// based on the "Basic USB Example" from ATMEL (doc6123.pdf)
//-----------------------------------------------------------------------------
#include "usb_cdc_apis.h"
#include "at91sam7s512.h"
#include "proxmark3_arm.h"
#include "usart_defs.h"
#include "ticks_apis.h"
#include "usb_read_ng.h"
#include "usb_cdc_desc.h"
/*
AT91SAM7S256 USB Device Port
• Embedded 328-byte dual-port RAM for endpoints
• Four endpoints
– Endpoint 0: 8 bytes
– Endpoint 1 and 2: 64 bytes ping-pong
– Endpoint 3: 64 bytes
– Ping-pong Mode (two memory banks) for bulk endpoints
*/
// EP for CDC definition
#define AT91C_EP_CONTROL 0
#define AT91C_EP_OUT 1 // cfg bulk out - 0x01
#define AT91C_EP_IN 2 // cfg bulk in - 0x82
#define AT91C_EP_NOTIFY 3 // cfg cdc notification interrup - 0x83
// The definition of endpoint size has been moved back from the original file to this source file.
// Because the usb_cdc.h header file is now a universally defined header file.
#define AT91C_USB_EP_CONTROL_SIZE 8
#define AT91C_USB_EP_OUT_SIZE 64
#define AT91C_USB_EP_IN_SIZE 64
/* WCID specific Request Code */
#define MS_OS_DESCRIPTOR_INDEX 0xEE
#define MS_VENDOR_CODE 0x1C
#define MS_EXTENDED_COMPAT_ID 0x04
#define MS_EXTENDED_PROPERTIES 0x05
#define MS_WCID_GET_DESCRIPTOR 0xC0
#define MS_WCID_GET_FEATURE_DESCRIPTOR 0xC1
/* USB standard request code */
#define STD_GET_STATUS_ZERO 0x0080
#define STD_GET_STATUS_INTERFACE 0x0081
#define STD_GET_STATUS_ENDPOINT 0x0082
#define STD_CLEAR_FEATURE_ZERO 0x0100
#define STD_CLEAR_FEATURE_INTERFACE 0x0101
#define STD_CLEAR_FEATURE_ENDPOINT 0x0102
#define STD_SET_FEATURE_ZERO 0x0300
#define STD_SET_FEATURE_INTERFACE 0x0301
#define STD_SET_FEATURE_ENDPOINT 0x0302
#define STD_SET_ADDRESS 0x0500
#define STD_GET_DESCRIPTOR 0x0680
#define STD_SET_DESCRIPTOR 0x0700
#define STD_GET_CONFIGURATION 0x0880
#define STD_SET_CONFIGURATION 0x0900
#define STD_GET_INTERFACE 0x0A81
#define STD_SET_INTERFACE 0x0B01
#define STD_SYNCH_FRAME 0x0C82
/* CDC Class Specific Request Code */
#define GET_LINE_CODING 0x21A1
#define SET_LINE_CODING 0x2021
#define SET_CONTROL_LINE_STATE 0x2221
// !!!! NOTE: If we need inline a function, then don't set the variables to static.
bool isAsyncRequestFinished = false;
AT91PS_UDP pUdp = AT91C_BASE_UDP;
static uint8_t btConfiguration = 0;
static uint8_t btConnection = 0;
static uint8_t btReceiveBank = AT91C_UDP_RX_DATA_BK0;
// -- pre def functions
void AT91F_USB_SendData(AT91PS_UDP pudp, const char *pData, uint32_t length);
void AT91F_USB_SendZlp(AT91PS_UDP pudp);
void AT91F_USB_SendStall(AT91PS_UDP pudp);
void AT91F_CDC_Enumerate(void);
// --
void SetUSBreconnect(int value);
int GetUSBreconnect(void);
void SetUSBconfigured(int value);
int GetUSBconfigured(void);
static const char *getStringDescriptor(uint8_t idx) {
switch (idx) {
case 0:
return StrLanguageCodes;
case 1:
return StrManufacturer;
case 2:
return StrProduct;
case 3:
return StrSerialNumber;
case MS_OS_DESCRIPTOR_INDEX:
return StrMS_OSDescriptor;
default:
return (NULL);
}
}
// Bitmap for all status bits in CSR which must be written as 1 to cause no effect
#define REG_NO_EFFECT_1_ALL AT91C_UDP_RX_DATA_BK0 | AT91C_UDP_RX_DATA_BK1 \
|AT91C_UDP_STALLSENT | AT91C_UDP_RXSETUP \
|AT91C_UDP_TXCOMP
// Clear flags in the UDP_CSR register and waits for synchronization
#define UDP_CLEAR_EP_FLAGS(endpoint, flags) { \
volatile unsigned int reg; \
reg = pUdp->UDP_CSR[(endpoint)]; \
reg |= REG_NO_EFFECT_1_ALL; \
reg &= ~(flags); \
pUdp->UDP_CSR[(endpoint)] = reg; \
}
// reset flags in the UDP_CSR register and waits for synchronization
#define UDP_SET_EP_FLAGS(endpoint, flags) { \
volatile unsigned int reg; \
reg = pUdp->UDP_CSR[(endpoint)]; \
reg |= REG_NO_EFFECT_1_ALL; \
reg |= (flags); \
pUdp->UDP_CSR[(endpoint)] = reg; \
}
typedef struct {
uint32_t BitRate;
uint8_t Format;
uint8_t ParityType;
uint8_t DataBits;
} AT91S_CDC_LINE_CODING, *AT91PS_CDC_LINE_CODING;
static AT91S_CDC_LINE_CODING line = { // purely informative, actual values don't matter
USART_BAUD_RATE, // baudrate
0, // 1 Stop Bit
0, // None Parity
8 // 8 Data bits
};
#ifndef AS_BOOTROM
// buffer of read_ng apis.
static uint8_t usb_read_ng_buffer[64] = {0};
// Implemented for read_ng
static bool usb_read_ng_link_ready(void) {
// old: if (usb_check() == false)
return usb_check(); // reuse 'usb_check()'
}
// Implemented for read_ng
static bool usb_read_ng_data_ready(void) {
// old: if ((pUdp->UDP_CSR[AT91C_EP_OUT] & bank))
return (pUdp->UDP_CSR[AT91C_EP_OUT] & btReceiveBank) != 0;
}
// Implemented for read_ng
static uint16_t usb_read_ng_data_available(void) {
// old: uint16_t available = (((pUdp->UDP_CSR[AT91C_EP_OUT] & AT91C_UDP_RXBYTECNT) >> 16) & 0x7FF);
return usb_available_length();
}
// Implemented for read_ng
static uint8_t usb_read_ng_data_read(void) {
return pUdp->UDP_FDR[AT91C_EP_OUT];
}
// Implemented for read_ng
static void usb_read_ng_clear(void) {
// flip bank
UDP_CLEAR_EP_FLAGS(AT91C_EP_OUT, btReceiveBank)
if (btReceiveBank == AT91C_UDP_RX_DATA_BK0) {
btReceiveBank = AT91C_UDP_RX_DATA_BK1;
} else {
btReceiveBank = AT91C_UDP_RX_DATA_BK0;
}
}
// Instance for 'read_ng' apis
static const usb_read_ng_config_t g_usb_read_ng_config = {
.is_link_ready = usb_read_ng_link_ready,
.is_data_ready = usb_read_ng_data_ready,
.get_byte_count = usb_read_ng_data_available,
.read_fifo = usb_read_ng_data_read,
.clear_ready = usb_read_ng_clear,
.buffer = usb_read_ng_buffer,
.buffer_size = sizeof(usb_read_ng_buffer),
.timeout = 0x1FFF
};
#endif
/*
*----------------------------------------------------------------------------
* \fn usb_disable
* \brief This function deactivates the USB device
*----------------------------------------------------------------------------
*/
void usb_disable(void) {
// Disconnect the USB device
AT91C_BASE_PIOA->PIO_ODR = GPIO_USB_PU;
// Clear all lingering interrupts
if (pUdp->UDP_ISR & AT91C_UDP_ENDBUSRES) {
pUdp->UDP_ICR = AT91C_UDP_ENDBUSRES;
}
}
/*
*----------------------------------------------------------------------------
* \fn usb_enable
* \brief This function Activates the USB device
*----------------------------------------------------------------------------
*/
void usb_enable(void) {
// Set the PLL USB Divider
AT91C_BASE_CKGR->CKGR_PLLR |= AT91C_CKGR_USBDIV_1 ;
// Specific Chip USB Initialisation
// Enables the 48MHz USB clock UDPCK and System Peripheral USB Clock
AT91C_BASE_PMC->PMC_SCER |= AT91C_PMC_UDP;
AT91C_BASE_PMC->PMC_PCER = (1 << AT91C_ID_UDP);
AT91C_BASE_UDP->UDP_FADDR = 0;
AT91C_BASE_UDP->UDP_GLBSTATE = 0;
// Enable UDP PullUp (USB_DP_PUP) : enable & Clear of the corresponding PIO
// Set in PIO mode and Configure in Output
AT91C_BASE_PIOA->PIO_PER = GPIO_USB_PU; // Set in PIO mode
AT91C_BASE_PIOA->PIO_OER = GPIO_USB_PU; // Configure as Output
// Clear for set the Pullup resistor
AT91C_BASE_PIOA->PIO_CODR = GPIO_USB_PU;
// Disconnect and reconnect USB controller for 100ms
usb_disable();
SpinDelayUs(100 * 1000);
// Wait for a short while
//for (volatile size_t i=0; i<0x100000; i++) {};
// Reconnect USB reconnect
AT91C_BASE_PIOA->PIO_SODR = GPIO_USB_PU;
AT91C_BASE_PIOA->PIO_OER = GPIO_USB_PU;
#ifndef AS_BOOTROM
// setup read_ng implement.
usb_read_ng_init(&g_usb_read_ng_config);
#endif
}
static int usb_reconnect = 0;
static int usb_configured = 0;
void SetUSBreconnect(int value) {
usb_reconnect = value;
}
int GetUSBreconnect(void) {
return usb_reconnect;
}
void SetUSBconfigured(int value) {
usb_configured = value;
}
int GetUSBconfigured(void) {
return usb_configured;
}
/*
*----------------------------------------------------------------------------
* \fn usb_check
* \brief Test if the device is configured and handle enumeration
*----------------------------------------------------------------------------
*/
bool usb_check(void) {
/*
// reconnected ONCE and
if ( !USB_ATTACHED() ){
usb_reconnect = 1;
return false;
}
// only one time after USB been disengaged and re-engaged
if ( USB_ATTACHED() && usb_reconnect == 1 ) {
if ( usb_configured == 0) {
usb_disable();
usb_enable();
AT91F_CDC_Enumerate();
usb_configured = 1;
return false;
}
}
*/
// interrupt status register
AT91_REG isr = pUdp->UDP_ISR;
// end of bus reset
if (isr & AT91C_UDP_ENDBUSRES) {
pUdp->UDP_ICR = AT91C_UDP_ENDBUSRES;
// reset all endpoints
pUdp->UDP_RSTEP = (unsigned int) - 1;
pUdp->UDP_RSTEP = 0;
// Enable the function
pUdp->UDP_FADDR = AT91C_UDP_FEN;
// Configure endpoint 0 (enable control endpoint)
pUdp->UDP_CSR[AT91C_EP_CONTROL] = (AT91C_UDP_EPEDS | AT91C_UDP_EPTYPE_CTRL);
} else if (isr & AT91C_UDP_EPINT0) {
pUdp->UDP_ICR = AT91C_UDP_EPINT0;
AT91F_CDC_Enumerate();
}
/*
else if (isr & AT91C_UDP_EPINT3 ) {
pUdp->UDP_ICR = AT91C_UDP_EPINT3;
AT91F_CDC_Enumerate();
//pUdp->UDP_ICR |= AT91C_UDP_EPINT3;
}
*/
return (btConfiguration) ? true : false;
}
/*
*----------------------------------------------------------------------------
* \fn usb_poll
* \brief Test if the device link ok and data received.
*----------------------------------------------------------------------------
*/
bool usb_poll(void) {
if (usb_check() == false) {
return false;
}
return (pUdp->UDP_CSR[AT91C_EP_OUT] & btReceiveBank);
}
/*
*----------------------------------------------------------------------------
* \fn usb_available_length
* \brief Get data received length of out endpoint.
*----------------------------------------------------------------------------
*/
FORCE_INLINE uint16_t usb_available_length(void) {
return (((pUdp->UDP_CSR[AT91C_EP_OUT] & AT91C_UDP_RXBYTECNT) >> 16) & 0x7FF);
}
/**
In github PR #129, some users appears to get a false positive from
usb_poll, which returns true, but the usb_read operation
still returns 0.
This check is basically the same as above, but also checks
that the length available to read is non-zero, thus hopefully fixes the
bug.
**/
bool usb_poll_validate_length(void) {
// Reuse 'usb_poll()' implemented.
if (usb_poll() == false) {
return false;
}
// Why code this: return (((pUdp->UDP_CSR[AT91C_EP_OUT] & AT91C_UDP_RXBYTECNT) >> 16) > 0);
// For speed? but 'usb_available_length()' is a inline function.
return (usb_available_length() > 0);
}
/*
*----------------------------------------------------------------------------
* \fn usb_read
* \brief Read available data from Endpoint 1 OUT (host to device, blocking read.)
*----------------------------------------------------------------------------
*/
uint32_t usb_read(uint8_t *data, size_t len) {
if (len == 0) {
return 0;
}
uint8_t bank = btReceiveBank;
uint16_t packetSize, nbBytesRcv = 0;
uint16_t time_out = 0;
while (len) {
if (usb_check() == false) {
break;
}
if (pUdp->UDP_CSR[AT91C_EP_OUT] & bank) {
packetSize = (((pUdp->UDP_CSR[AT91C_EP_OUT] & AT91C_UDP_RXBYTECNT) >> 16) & 0x7FF);
packetSize = MIN(packetSize, len);
len -= packetSize;
while (packetSize--) {
data[nbBytesRcv++] = pUdp->UDP_FDR[AT91C_EP_OUT];
}
// flip bank
UDP_CLEAR_EP_FLAGS(AT91C_EP_OUT, bank)
if (bank == AT91C_UDP_RX_DATA_BK0) {
bank = AT91C_UDP_RX_DATA_BK1;
} else {
bank = AT91C_UDP_RX_DATA_BK0;
}
}
if (time_out++ == 0x1FFF) {
break;
}
}
btReceiveBank = bank;
return nbBytesRcv;
}
/*
*----------------------------------------------------------------------------
* \fn usb_write
* \brief Send through endpoint 2 (device to host, blocking write.)
*----------------------------------------------------------------------------
*/
int usb_write(const uint8_t *data, const size_t len) {
if (len == 0) {
return PM3_EINVARG;
}
if (usb_check() == false) {
return PM3_EIO;
}
// can we write?
if ((pUdp->UDP_CSR[AT91C_EP_IN] & AT91C_UDP_TXPKTRDY) != 0) {
return PM3_EIO;
}
size_t length = len;
uint32_t cpt = 0;
// send first chunk
cpt = MIN(length, AT91C_USB_EP_IN_SIZE);
length -= cpt;
while (cpt--) {
pUdp->UDP_FDR[AT91C_EP_IN] = *data++;
}
UDP_SET_EP_FLAGS(AT91C_EP_IN, AT91C_UDP_TXPKTRDY);
while (!(pUdp->UDP_CSR[AT91C_EP_IN] & AT91C_UDP_TXPKTRDY)) {};
while (length) {
// Send next chunk
cpt = MIN(length, AT91C_USB_EP_IN_SIZE);
length -= cpt;
while (cpt--) {
pUdp->UDP_FDR[AT91C_EP_IN] = *data++;
}
// Wait for previous chunk to be sent
// (iceman) when is the bankswapping done?
while (!(pUdp->UDP_CSR[AT91C_EP_IN] & AT91C_UDP_TXCOMP)) {
if (usb_check() == false) {
return PM3_EIO;
}
}
UDP_CLEAR_EP_FLAGS(AT91C_EP_IN, AT91C_UDP_TXCOMP);
while (pUdp->UDP_CSR[AT91C_EP_IN] & AT91C_UDP_TXCOMP) {};
UDP_SET_EP_FLAGS(AT91C_EP_IN, AT91C_UDP_TXPKTRDY);
while (!(pUdp->UDP_CSR[AT91C_EP_IN] & AT91C_UDP_TXPKTRDY)) {};
}
// Wait for the end of transfer
while (!(pUdp->UDP_CSR[AT91C_EP_IN] & AT91C_UDP_TXCOMP)) {
if (usb_check() == false) {
return PM3_EIO;
}
}
UDP_CLEAR_EP_FLAGS(AT91C_EP_IN, AT91C_UDP_TXCOMP);
while (pUdp->UDP_CSR[AT91C_EP_IN] & AT91C_UDP_TXCOMP) {};
if (len % AT91C_USB_EP_IN_SIZE == 0) {
// like AT91F_USB_SendZlp(), in non ping-pong mode
UDP_SET_EP_FLAGS(AT91C_EP_IN, AT91C_UDP_TXPKTRDY);
while (!(pUdp->UDP_CSR[AT91C_EP_IN] & AT91C_UDP_TXCOMP)) {};
UDP_CLEAR_EP_FLAGS(AT91C_EP_IN, AT91C_UDP_TXCOMP);
while (pUdp->UDP_CSR[AT91C_EP_IN] & AT91C_UDP_TXCOMP) {};
}
return PM3_SUCCESS;
}
/*
*----------------------------------------------------------------------------
* \fn async_usb_write_start
* \brief Start async write process
* \return PM3_EIO if USB is invalid, PM3_SUCCESS if it is ready for write
*
* This function checks if the USB is connected, and wait until the FIFO
* is ready to be filled.
*
* Warning: usb_write() should not be called between
* async_usb_write_start() and async_usb_write_stop().
*----------------------------------------------------------------------------
*/
int async_usb_write_start(void) {
if (usb_check() == false) {
return PM3_EIO;
}
while (pUdp->UDP_CSR[AT91C_EP_IN] & AT91C_UDP_TXPKTRDY) {
if (usb_check() == false) {
return PM3_EIO;
}
}
isAsyncRequestFinished = false;
return PM3_SUCCESS;
}
/*
*----------------------------------------------------------------------------
* \fn async_usb_write_pushByte
* \brief Push one byte to the FIFO of IN endpoint (time-critical)
*
* This function simply push a byte to the FIFO of IN endpoint.
* The FIFO size is AT91C_USB_EP_IN_SIZE. Make sure this function is not called
* over AT91C_USB_EP_IN_SIZE times between each async_usb_write_requestWrite().
*----------------------------------------------------------------------------
*/
inline void async_usb_write_pushByte(uint8_t data) {
pUdp->UDP_FDR[AT91C_EP_IN] = data;
isAsyncRequestFinished = false;
}
/*
*----------------------------------------------------------------------------
* \fn async_usb_write_requestWrite
* \brief Request a write operation (time-critical)
* \return false if the last write request is not finished, true if success
*
* This function requests a write operation from FIFO to the USB bus,
* and switch the internal banks of FIFO. It doesn't wait for the end of
* transmission from FIFO to the USB bus.
*
* Note: This function doesn't check if the usb is valid, as it is
* time-critical.
*----------------------------------------------------------------------------
*/
inline bool async_usb_write_requestWrite(void) {
// check if last request is finished
if (pUdp->UDP_CSR[AT91C_EP_IN] & AT91C_UDP_TXPKTRDY) {
return false;
}
// clear transmission completed flag
UDP_CLEAR_EP_FLAGS(AT91C_EP_IN, AT91C_UDP_TXCOMP);
while (pUdp->UDP_CSR[AT91C_EP_IN] & AT91C_UDP_TXCOMP) {};
// start of transmission
UDP_SET_EP_FLAGS(AT91C_EP_IN, AT91C_UDP_TXPKTRDY);
// hack: no need to wait if UDP_CSR and UDP_FDR are not used immediately.
// while (!(pUdp->UDP_CSR[AT91C_EP_IN] & AT91C_UDP_TXPKTRDY)) {};
isAsyncRequestFinished = true;
return true;
}
/*
*----------------------------------------------------------------------------
* \fn async_usb_write_stop
* \brief Stop async write process
* \return PM3_EIO if USB is invalid, PM3_SUCCESS if data is written
*
* This function makes sure the data left in the FIFO is written to the
* USB bus.
*
* Warning: usb_write() should not be called between
* async_usb_write_start() and async_usb_write_stop().
*----------------------------------------------------------------------------
*/
int async_usb_write_stop(void) {
// Wait for the end of transfer
while (pUdp->UDP_CSR[AT91C_EP_IN] & AT91C_UDP_TXPKTRDY) {
if (usb_check() == false) {
return PM3_EIO;
}
}
// clear transmission completed flag
UDP_CLEAR_EP_FLAGS(AT91C_EP_IN, AT91C_UDP_TXCOMP);
while (pUdp->UDP_CSR[AT91C_EP_IN] & AT91C_UDP_TXCOMP) {};
// FIFO is not empty, request a write in non-ping-pong mode
if (isAsyncRequestFinished == false) {
UDP_SET_EP_FLAGS(AT91C_EP_IN, AT91C_UDP_TXPKTRDY);
while (!(pUdp->UDP_CSR[AT91C_EP_IN] & AT91C_UDP_TXCOMP)) {
if (usb_check() == false) {
return PM3_EIO;
}
}
UDP_CLEAR_EP_FLAGS(AT91C_EP_IN, AT91C_UDP_TXCOMP);
while (pUdp->UDP_CSR[AT91C_EP_IN] & AT91C_UDP_TXCOMP) {};
}
return PM3_SUCCESS;
}
/*
*----------------------------------------------------------------------------
* \fn AT91F_USB_SendData
* \brief Send Data through the control endpoint
*----------------------------------------------------------------------------
*/
void AT91F_USB_SendData(AT91PS_UDP pudp, const char *pData, uint32_t length) {
AT91_REG csr;
do {
uint32_t cpt = MIN(length, AT91C_USB_EP_CONTROL_SIZE);
length -= cpt;
while (cpt--) {
pudp->UDP_FDR[AT91C_EP_CONTROL] = *pData++;
}
if (pudp->UDP_CSR[AT91C_EP_CONTROL] & AT91C_UDP_TXCOMP) {
UDP_CLEAR_EP_FLAGS(AT91C_EP_CONTROL, AT91C_UDP_TXCOMP);
while (pudp->UDP_CSR[AT91C_EP_CONTROL] & AT91C_UDP_TXCOMP) {};
}
UDP_SET_EP_FLAGS(AT91C_EP_CONTROL, AT91C_UDP_TXPKTRDY);
do {
csr = pudp->UDP_CSR[AT91C_EP_CONTROL];
// Data IN stage has been stopped by a status OUT
if (csr & AT91C_UDP_RX_DATA_BK0) {
UDP_CLEAR_EP_FLAGS(AT91C_EP_CONTROL, AT91C_UDP_RX_DATA_BK0)
return;
}
} while (!(csr & AT91C_UDP_TXCOMP));
} while (length);
if (pudp->UDP_CSR[AT91C_EP_CONTROL] & AT91C_UDP_TXCOMP) {
UDP_CLEAR_EP_FLAGS(AT91C_EP_CONTROL, AT91C_UDP_TXCOMP);
while (pudp->UDP_CSR[AT91C_EP_CONTROL] & AT91C_UDP_TXCOMP) {};
}
}
//*----------------------------------------------------------------------------
//* \fn AT91F_USB_SendZlp
//* \brief Send zero length packet through the control endpoint
//*----------------------------------------------------------------------------
void AT91F_USB_SendZlp(AT91PS_UDP pudp) {
UDP_SET_EP_FLAGS(AT91C_EP_CONTROL, AT91C_UDP_TXPKTRDY);
// for non ping-pong operation, wait until the FIFO is released
// the flag for FIFO released is AT91C_UDP_TXCOMP rather than AT91C_UDP_TXPKTRDY
while (!(pudp->UDP_CSR[AT91C_EP_CONTROL] & AT91C_UDP_TXCOMP)) {};
UDP_CLEAR_EP_FLAGS(AT91C_EP_CONTROL, AT91C_UDP_TXCOMP);
while (pudp->UDP_CSR[AT91C_EP_CONTROL] & AT91C_UDP_TXCOMP) {};
}
//*----------------------------------------------------------------------------
//* \fn AT91F_USB_SendStall
//* \brief Stall the control endpoint
//*----------------------------------------------------------------------------
void AT91F_USB_SendStall(AT91PS_UDP pudp) {
UDP_SET_EP_FLAGS(AT91C_EP_CONTROL, AT91C_UDP_FORCESTALL);
while (!(pudp->UDP_CSR[AT91C_EP_CONTROL] & AT91C_UDP_ISOERROR)) {};
UDP_CLEAR_EP_FLAGS(AT91C_EP_CONTROL, (AT91C_UDP_FORCESTALL | AT91C_UDP_ISOERROR));
while (pudp->UDP_CSR[AT91C_EP_CONTROL] & (AT91C_UDP_FORCESTALL | AT91C_UDP_ISOERROR)) {};
}
//*----------------------------------------------------------------------------
//* \fn AT91F_CDC_Enumerate
//* \brief This function is a callback invoked when a SETUP packet is received
//* problem:
//* 1. this is for USB endpoint0. the control endpoint.
//* 2. mixed with CDC ACM endpoint3 , interrupt, control endpoint
//*----------------------------------------------------------------------------
void AT91F_CDC_Enumerate(void) {
uint8_t bmRequestType, bRequest;
uint16_t wValue, wIndex, wLength, wStatus;
if (!(pUdp->UDP_CSR[AT91C_EP_CONTROL] & AT91C_UDP_RXSETUP)) {
return;
}
bmRequestType = pUdp->UDP_FDR[AT91C_EP_CONTROL];
bRequest = pUdp->UDP_FDR[AT91C_EP_CONTROL];
wValue = (pUdp->UDP_FDR[AT91C_EP_CONTROL] & 0xFF);
wValue |= (pUdp->UDP_FDR[AT91C_EP_CONTROL] << 8);
wIndex = (pUdp->UDP_FDR[AT91C_EP_CONTROL] & 0xFF);
wIndex |= (pUdp->UDP_FDR[AT91C_EP_CONTROL] << 8);
wLength = (pUdp->UDP_FDR[AT91C_EP_CONTROL] & 0xFF);
wLength |= (pUdp->UDP_FDR[AT91C_EP_CONTROL] << 8);
if (bmRequestType & 0x80) { // Data Phase Transfer Direction Device to Host
UDP_SET_EP_FLAGS(AT91C_EP_CONTROL, AT91C_UDP_DIR);
while (!(pUdp->UDP_CSR[AT91C_EP_CONTROL] & AT91C_UDP_DIR)) {};
}
UDP_CLEAR_EP_FLAGS(AT91C_EP_CONTROL, AT91C_UDP_RXSETUP);
while ((pUdp->UDP_CSR[AT91C_EP_CONTROL] & AT91C_UDP_RXSETUP)) {};
/*
if ( bRequest == MS_VENDOR_CODE) {
if ( bmRequestType == MS_WCID_GET_DESCRIPTOR ) { // C0
if ( wIndex == MS_EXTENDED_COMPAT_ID ) { // 4
//AT91F_USB_SendData(pUdp, CompatIDFeatureDescriptor, MIN(sizeof(CompatIDFeatureDescriptor), wLength));
//return;
}
}
if ( bmRequestType == MS_WCID_GET_FEATURE_DESCRIPTOR ) { //C1
// if ( wIndex == MS_EXTENDED_PROPERTIES ) { // 5 - winusb bug with wIndex == interface index, so I just send it always)
//AT91F_USB_SendData(pUdp, OSprop, MIN(sizeof(OSprop), wLength));
//return;
// }
}
}
*/
// Handle supported standard device request Cf Table 9-3 in USB specification Rev 1.1
switch ((bRequest << 8) | bmRequestType) {
case STD_GET_DESCRIPTOR: {
if (wValue == 0x100) { // Return Device Descriptor
AT91F_USB_SendData(pUdp, devDescriptor, MIN(sizeof(devDescriptor), wLength));
} else if (wValue == 0x200) { // Return Configuration Descriptor
AT91F_USB_SendData(pUdp, cfgDescriptor, MIN(sizeof(cfgDescriptor), wLength));
} else if ((wValue & 0xF00) == 0xF00) { // Return BOS Descriptor
AT91F_USB_SendData(pUdp, bosDescriptor, MIN(sizeof(bosDescriptor), wLength));
} else if ((wValue & 0x300) == 0x300) { // Return String Descriptor
const char *strDescriptor = getStringDescriptor(wValue & 0xff);
if (strDescriptor != NULL) {
AT91F_USB_SendData(pUdp, strDescriptor, MIN(strDescriptor[0], wLength));
} else {
AT91F_USB_SendStall(pUdp);
}
} else {
AT91F_USB_SendStall(pUdp);
}
}
break;
case STD_SET_ADDRESS:
AT91F_USB_SendZlp(pUdp);
pUdp->UDP_FADDR = (AT91C_UDP_FEN | (wValue & 0x7F));
pUdp->UDP_GLBSTATE = (wValue) ? AT91C_UDP_FADDEN : 0;
break;
case STD_SET_CONFIGURATION:
/*
* Set or clear the device "configured" state.
* The LSB of wValue is the "Configuration Number". If this value is non-zero,
* it should be the same number as defined in the Configuration Descriptor;
* otherwise an error must have occurred.
* This device has only one configuration and its Config Number is CONF_NB (= 1).
*/
AT91F_USB_SendZlp(pUdp);
btConfiguration = wValue;
pUdp->UDP_GLBSTATE = (wValue) ? AT91C_UDP_CONFG : AT91C_UDP_FADDEN;
// make sure we are not stalled
/*
UDP_CLEAR_EP_FLAGS(AT91C_EP_OUT , AT91C_UDP_FORCESTALL);
UDP_CLEAR_EP_FLAGS(AT91C_EP_IN , AT91C_UDP_FORCESTALL);
UDP_CLEAR_EP_FLAGS(AT91C_EP_NOTIFY, AT91C_UDP_FORCESTALL);
*/
// enable endpoints
pUdp->UDP_CSR[AT91C_EP_OUT] = (wValue) ? (AT91C_UDP_EPEDS | AT91C_UDP_EPTYPE_BULK_OUT) : 0;
pUdp->UDP_CSR[AT91C_EP_IN] = (wValue) ? (AT91C_UDP_EPEDS | AT91C_UDP_EPTYPE_BULK_IN) : 0;
pUdp->UDP_CSR[AT91C_EP_NOTIFY] = (wValue) ? (AT91C_UDP_EPEDS | AT91C_UDP_EPTYPE_INT_IN) : 0;
break;
case STD_GET_CONFIGURATION:
AT91F_USB_SendData(pUdp, (char *) & (btConfiguration), sizeof(btConfiguration));
break;
case STD_GET_STATUS_ZERO:
wStatus = 0; // Device is Bus powered, remote wakeup disabled
AT91F_USB_SendData(pUdp, (char *) &wStatus, sizeof(wStatus));
break;
case STD_GET_STATUS_INTERFACE:
wStatus = 0; // reserved for future use
AT91F_USB_SendData(pUdp, (char *) &wStatus, sizeof(wStatus));
break;
case STD_GET_STATUS_ENDPOINT:
wStatus = 0;
wIndex &= 0x0F;
if ((pUdp->UDP_GLBSTATE & AT91C_UDP_CONFG) && (wIndex <= AT91C_EP_NOTIFY)) {
wStatus = (pUdp->UDP_CSR[wIndex] & AT91C_UDP_EPEDS) ? 0 : 1;
AT91F_USB_SendData(pUdp, (char *) &wStatus, sizeof(wStatus));
} else if ((pUdp->UDP_GLBSTATE & AT91C_UDP_FADDEN) && (wIndex == AT91C_EP_CONTROL)) {
wStatus = (pUdp->UDP_CSR[wIndex] & AT91C_UDP_EPEDS) ? 0 : 1;
AT91F_USB_SendData(pUdp, (char *) &wStatus, sizeof(wStatus));
} else {
AT91F_USB_SendStall(pUdp);
}
break;
case STD_SET_FEATURE_ZERO:
AT91F_USB_SendStall(pUdp);
break;
case STD_SET_FEATURE_INTERFACE:
AT91F_USB_SendZlp(pUdp);
break;
case STD_SET_FEATURE_ENDPOINT:
wIndex &= 0x0F;
if ((wValue == 0) && (wIndex >= AT91C_EP_OUT) && (wIndex <= AT91C_EP_NOTIFY)) {
pUdp->UDP_CSR[wIndex] = 0;
AT91F_USB_SendZlp(pUdp);
} else {
AT91F_USB_SendStall(pUdp);
}
break;
case STD_CLEAR_FEATURE_ZERO:
AT91F_USB_SendStall(pUdp);
break;
case STD_CLEAR_FEATURE_INTERFACE:
AT91F_USB_SendZlp(pUdp);
break;
case STD_CLEAR_FEATURE_ENDPOINT:
wIndex &= 0x0F;
if ((wValue == 0) && (wIndex >= AT91C_EP_OUT) && (wIndex <= AT91C_EP_NOTIFY)) {
if (wIndex == AT91C_EP_OUT) {
pUdp->UDP_CSR[AT91C_EP_OUT] = (AT91C_UDP_EPEDS | AT91C_UDP_EPTYPE_BULK_OUT);
} else if (wIndex == AT91C_EP_IN) {
pUdp->UDP_CSR[AT91C_EP_IN] = (AT91C_UDP_EPEDS | AT91C_UDP_EPTYPE_BULK_IN);
} else if (wIndex == AT91C_EP_NOTIFY) {
pUdp->UDP_CSR[AT91C_EP_NOTIFY] = (AT91C_UDP_EPEDS | AT91C_UDP_EPTYPE_INT_IN);
}
AT91F_USB_SendZlp(pUdp);
} else {
AT91F_USB_SendStall(pUdp);
}
break;
// handle CDC class requests
case SET_LINE_CODING: {
/*
uint8_t i;
for ( i = 0 ; i < 7 ; i++ ) {
((uint8_t*)&line)[i] = pUdp->UDP_FDR[AT91C_EP_CONTROL];
} */
// ignore SET_LINE_CODING...
while (!(pUdp->UDP_CSR[AT91C_EP_CONTROL] & AT91C_UDP_RX_DATA_BK0)) {};
UDP_CLEAR_EP_FLAGS(AT91C_EP_CONTROL, AT91C_UDP_RX_DATA_BK0);
AT91F_USB_SendZlp(pUdp);
break;
}
case GET_LINE_CODING:
AT91F_USB_SendData(pUdp, (char *) &line, MIN(sizeof(line), wLength));
break;
case SET_CONTROL_LINE_STATE:
btConnection = wValue;
AT91F_USB_SendZlp(pUdp);
break;
default:
AT91F_USB_SendStall(pUdp);
break;
}
}
//*----------------------------------------------------------------------------
//* \fn usb_get_ep_size
//* \brief This function can get usb endpoint buffer size
//*----------------------------------------------------------------------------
void usb_get_ep_size(uint32_t *epCtl, uint32_t *epIn, uint32_t *epOut) {
if (epCtl) *epCtl = AT91C_USB_EP_CONTROL_SIZE;
if (epIn) *epIn = AT91C_USB_EP_IN_SIZE;
if (epOut) *epOut = AT91C_USB_EP_OUT_SIZE;
}
+324
View File
@@ -0,0 +1,324 @@
#include <stdbool.h>
#include <stdint.h>
#include "usb_cdc_desc.h"
#include "usb_cdc_apis.h"
#ifndef LBYTE
#define LBYTE(x) ((uint8_t)(x & 0x00FF)) /*!< low byte define */
#endif
#ifndef HBYTE
#define HBYTE(x) ((uint8_t)((x & 0xFF00) >>8)) /*!< high byte define*/
#endif
const char devDescriptor[18] = {
/* Device descriptor */
0x12, // Length
0x01, // Descriptor Type (DEVICE)
0x00, 0x02, // Complies with USB Spec. Release (0200h = release 2.00) 0210 == release 2.10
2, // Device Class: Communication Device Class
0, // Device Subclass: CDC class sub code ACM [ice 0x02 = win10 virtual comport ]
0, // Device Protocol: CDC Device protocol (unused)
USB_CDC_DESC_MAX_EP0_SIZE, // MaxPacketSize0: The maximum packet size for endpoint 0
0xc4, 0x9a, // Vendor ID [0x9ac4 = J. Westhues]
0x8f, 0x4b, // Product ID [0x4b8f = Proxmark-3 RFID Instrument]
0x00, 0x01, // BCD Device release number (1.00)
1, // index Manufacturer
2, // index Product
3, // index SerialNumber
1 // Number of Configs
};
const char cfgDescriptor[67] = {
/* Configuration 1 descriptor */
// -----------------------------
9, // Length
0x02, // Descriptor Type
(9 + 9 + 5 + 5 + 4 + 5 + 7 + 9 + 7 + 7), 0, // Total Length 2 EP + Control
2, // Number of Interfaces
1, // Index value of this Configuration (used in SetConfiguration from Host)
0, // Configuration string index
USB_CDC_DESC_CFG_POWER_MODE, // Attributes 0xA0
0xFA, // Max Power consumption
// IAD to associate the one CDC interface
// --------------------------------------
/*
8, // Length
USB_DESCRIPTOR_IAD, // IAD_DESCRIPTOR (0x0B)
0, // CDC_INT_INTERFACE NUMBER (
2, // IAD INTERFACE COUNT (two interfaces)
2, // Function Class: CDC_CLASS
2, // Function SubClass: ACM
1, // Function Protocol: v.25term
0, // iInterface
*/
/* Interface 0 Descriptor */
/* CDC Communication Class Interface Descriptor Requirement for Notification*/
// -----------------------------------------------------------
9, // Length
0x04, // Descriptor Type
0, // Interface Number
0, // Alternate Setting
1, // Number of Endpoints in this interface
2, // Interface Class code (Communication Interface Class)
2, // Interface Subclass code (Abstract Control Model)
1, // InterfaceProtocol (Common AT Commands, V.25term)
0, // iInterface
/* Header Functional Descriptor */
5, // Function Length
0x24, // Descriptor type: CS_INTERFACE
0, // Descriptor subtype: Header Functional Descriptor
0x10, 0x01, // bcd CDC:1.1
/* ACM Functional Descriptor */
4, // Function Length
0x24, // Descriptor Type: CS_INTERFACE
2, // Descriptor Subtype: Abstract Control Management Functional Descriptor
2, // Capabilities D1, Device supports the request combination of Set_Line_Coding, Set_Control_Line_State, Get_Line_Coding, and the notification Serial_State
/* Union Functional Descriptor */
5, // Function Length
0x24, // Descriptor Type: CS_INTERFACE
6, // Descriptor Subtype: Union Functional Descriptor
0, // MasterInterface: Communication Class Interface
1, // SlaveInterface0: Data Class Interface
/* Call Management Functional Descriptor */
5, // Function Length
0x24, // Descriptor Type: CS_INTERFACE
1, // Descriptor Subtype: Call Management Functional Descriptor
0, // Capabilities: Device sends/receives call management information only over the Communication Class interface. Device does not handle call management itself
1, // Data Interface: Data Class Interface
/* Protocol Functional Descriptor */
/*
6,
0x24, // Descriptor Type: CS_INTERFACE
0x0B, // Descriptor Subtype: Protocol Unit functional Descriptor
0xDD, // constant uniq ID of unit
0xFE, // protocol
*/
/* CDC Notification Endpoint descriptor */
// ---------------------------------------
7, // Length
0x05, // Descriptor Type
USB_CDC_DESC_INT_EPT, // EndpointAddress: Endpoint x - IN
0x03, // Attributes, Interrupt Transfer
// TODO: why set to ep0 size?
LBYTE(USB_CDC_DESC_MAX_EP0_SIZE), HBYTE(USB_CDC_DESC_MAX_EP0_SIZE), // MaxPacket Size
0xFF, // Interval polling
/* Interface 1 Descriptor */
/* CDC Data Class Interface 1 Descriptor Requirement */
9, // Length
0x04, // Descriptor Type
1, // Interface Number
0, // Alternate Setting
2, // Number of Endpoints
0x0A, // Interface Class: CDC Data interface class
0, // Interface Subclass: not used
0, // Interface Protocol: No class specific protocol required (usb spec)
0, // Interface
/* Endpoint descriptor */
7, // Length
0x05, // Descriptor Type
USB_CDC_DESC_BULK_OUT_EPT, // Endpoint Address: Endpoint 01 - OUT
0x02, // Attributes: BULK
LBYTE(USB_CDC_DESC_OUT_PACKET_SIZE), HBYTE(USB_CDC_DESC_OUT_PACKET_SIZE), // MaxPacket Size
0, // Interval: ignored for bulk
/* Endpoint descriptor */
7, // Length
0x05, // Descriptor Type
USB_CDC_DESC_BULK_IN_EPT, // Endpoint Address: Endpoint 02 - IN
0x02, // Attribute: BULK
LBYTE(USB_CDC_DESC_IN_PACKET_SIZE), HBYTE(USB_CDC_DESC_IN_PACKET_SIZE), // MaxPacket Size
0 // Interval: ignored for bulk
};
// BOS descriptor
const char bosDescriptor[12] = {
0x5,
0x0F, // DescriptorType for a BOS Descriptor.
0xC,
0x0,
0x1, // 1 device capability
0x7,
0x10, // USB_DEVICE_CAPABITY_TYPE,
0x2,
0x2, // LPM capability bit set
0x0,
0x0,
0x0
};
// Microsoft OS Extended Configuration Compatible ID Descriptor
/*
const char CompatIDFeatureDescriptor[] = {
0x28, 0x00, 0x00, 0x00, // Descriptor Length 40bytes (0x28)
0x00, 0x01, // Version ('1.0')
MS_EXTENDED_COMPAT_ID, 0x00, // Compatibility ID Descriptor Index 0x0004
0x01, // Number of sections. 0x1
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // Reserved (7bytes)
// -----function section 1------
0x00, // Interface Number #0
0x01, // reserved (0x1)
0x57, 0x49, 0x4E, 0x55, 0x53, 0x42, 0x00, 0x00, // Compatible ID ('WINUSB\0\0') (8bytes)
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // Sub-Compatible ID (8byte)
0x00, 0x00, 0x00, 0x00, 0x00, 0x00 // Reserved (6bytes)
};
*/
// Microsoft Extended Properties Feature Descriptor
/*
const char OSprop[] = {
// u32 Descriptor Length (10+132+64+102 == 308
0x34, 0x01, 0, 0,
// u16 Version ('1.0')
0, 1,
// u16 wIndex
MS_EXTENDED_PROPERTIES, 0,
// u16 wCount -- three section
3, 0,
// -----property section 1------
// u32 size ( 14+40+78 == 132)
132, 0, 0, 0,
// u32 type
1, 0, 0, 0, // unicode string
// u16 namelen (20*2 = 40)
40, 0,
// name DeviceInterfaceGUID
'D',0,'e',0,'v',0,'i',0,'c',0,'e',0,'I',0,'n',0,'t',0,'e',0,'r',0,'f',0,'a',0,'c',0,'e',0,'G',0,'U',0,'I',0,'D',0,0,0,
// u32 datalen (39*2 = 78)
78, 0, 0, 0,
// data {4D36E978-E325-11CE-BFC1-08002BE10318}
'{',0,'4',0,'d',0,'3',0,'6',0,'e',0,'9',0,'7',0,'8',0,'-',0,'e',0,'3',0,'2',0,'5',0,
'-',0,'1',0,'1',0,'c',0,'e',0,'-',0,'b',0,'f',0,'c',0,'1',0,'-',0,'0',0,'8',0,'0',0,
'0',0,'2',0,'b',0,'e',0,'1',0,'0',0,'3',0,'1',0,'8',0,'}',0,0,0,
// -----property section 2------
// u32 size ( 14+12+38 == 64)
64, 0, 0, 0,
// u32 type
1, 0, 0, 0, // unicode string
// u16 namelen (12)
12, 0,
// name Label
'L',0,'a',0,'b',0,'e',0,'l',0,0,0,
// u32 datalen ( 19*2 = 38 )
38, 0, 0, 0,
// data 'Awesome PM3 Device'
'A',0,'w',0,'e',0,'s',0,'o',0,'m',0,'e',0,' ',0,'P',0,'M',0,'3',0,' ',0,'D',0,'e',0,'v',0,'i',0,'c',0,'e',0,0,0,
// -----property section 3------
// u32 size ( 14+12+76 == 102)
102, 0, 0, 0,
// u32 type
2, 0, 0, 0, //Unicode string with environment variables
// u16 namelen (12)
12, 0,
// name Icons
'I',0,'c',0,'o',0,'n',0,'s',0,0,0,
// u32 datalen ( 38*2 == 76)
76, 0, 0, 0,
// data '%SystemRoot%\\system32\\Shell32.dll,-13'
'%',0,'S',0,'y',0,'s',0,'t',0,'e',0,'m',0,'R',0,'o',0,'o',0,'t',0,'%',0,
'\\',0,'s',0,'y',0,'s',0,'t',0,'e',0,'m',0,'3',0,'2',0,'\\',0,
'S',0,'h',0,'e',0,'l',0,'l',0,'3',0,'2',0,'.',0,'d',0,'l',0,'l',0,',',0,
'-',0,'1',0,'3',0,0,0
};
*/
const char StrLanguageCodes[4] = {
4, // Length
0x03, // Type is string
0x09, 0x04 // supported language Code 0 = 0x0409 (English)
};
// Note: ModemManager (Linux) ignores Proxmark3 devices by matching the
// manufacturer string "proxmark.org". Don't change this.
// or use the blacklisting file.
const char StrManufacturer[26] = {
26, // Length
0x03, // Type is string
'p', 0, 'r', 0, 'o', 0, 'x', 0, 'm', 0, 'a', 0, 'r', 0, 'k', 0, '.', 0, 'o', 0, 'r', 0, 'g', 0,
};
const char StrProduct[20] = {
20, // Length
0x03, // Type is string
'p', 0, 'r', 0, 'o', 0, 'x', 0, 'm', 0, 'a', 0, 'r', 0, 'k', 0, '3', 0
};
#ifndef WITH_FLASH // If there is no flash, then use a fixed(const) serial number.
const char StrSerialNumber[14] = {
14, // Length
0x03, // Type is string
'i', 0, 'c', 0, 'e', 0, 'm', 0, 'a', 0, 'n', 0
};
#else // WITH_FLASH is defined
// Manually calculated size of descriptor with unique ID:
// offset 0, lengt h 1: total length field
// offset 1, length 1: descriptor type field
// offset 2, length 12: 6x unicode chars (original string)
// offset 14, length 4: 2x unicode chars (underscores) [[ to avoid descriptor being (size % 8) == 0, OS bug workaround ]]
// offset 18, length 32: 16x unicode chars (8-byte serial as hex characters)
// ============================
// total: 50 bytes
#define USB_STRING_DESCRIPTOR_SERIAL_NUMBER_LENGTH 50
char StrSerialNumber[50] = {
14, // Length is initially identical to non-unique version ... The length updated at boot, if unique serial is available
0x03, // Type is string
'i', 0, 'c', 0, 'e', 0, 'm', 0, 'a', 0, 'n', 0,
'_', 0, '_', 0,
'x', 0, 'x', 0, 'x', 0, 'x', 0, 'x', 0, 'x', 0, 'x', 0, 'x', 0,
'x', 0, 'x', 0, 'x', 0, 'x', 0, 'x', 0, 'x', 0, 'x', 0, 'x', 0,
};
void usb_update_serial(uint64_t newSerialNumber) {
static bool configured = false; // TODO: enable by setting to false here...
if (configured) {
return;
}
// run this only once per boot... even if it fails to find serial number
configured = true;
// reject serial number if all-zero or all-ones
if ((newSerialNumber == 0x0000000000000000) || (newSerialNumber == 0xFFFFFFFFFFFFFFFF)) {
return;
}
// Descriptor is, effectively, initially identical to non-unique serial
// number because it reports the shorter length in the first byte.
// Convert uniqueID's eight bytes to 16 unicode characters in the
// descriptor and, finally, update the descriptor's length, which
// causes the serial number to become visible.
for (uint8_t i = 0; i < 8; i++) {
// order of nibbles chosen to match display order from `hw status`
uint8_t nibble1 = (newSerialNumber >> ((8 * i) + 4)) & 0xFu; // bitmasks [0xF0, 0xF000, 0xF00000, ... 0xF000000000000000]
uint8_t nibble2 = (newSerialNumber >> ((8 * i) + 0)) & 0xFu; // bitmasks [0x0F, 0x0F00, 0x0F0000, ... 0x0F00000000000000]
char c1 = nibble1 < 10 ? '0' + nibble1 : 'A' + (nibble1 - 10);
char c2 = nibble2 < 10 ? '0' + nibble2 : 'A' + (nibble2 - 10);
StrSerialNumber[18 + (4 * i) + 0] = c1; // [ 18, 22, .., 42, 46 ]
StrSerialNumber[18 + (4 * i) + 2] = c2; // [ 20, 24, .., 44, 48 ]
}
StrSerialNumber[0] = USB_STRING_DESCRIPTOR_SERIAL_NUMBER_LENGTH;
}
#endif
// size includes their own field.
const char StrMS_OSDescriptor[18] = {
18, // length 0x12
0x03, // Type is string
'M', 0, 'S', 0, 'F', 0, 'T', 0, '1', 0, '0', 0, '0', 0, USB_CDC_DESC_MS_VENDOR_CODE, 0
};
+74
View File
@@ -0,0 +1,74 @@
#ifndef USB_CDC_DESC_H
#define USB_CDC_DESC_H
#include <stdint.h>
// Please define USB-CDC configurations related to specific platforms here, such as endpoint size.
/**
* Power mode: Bit4-0 reserved, D7: bus power supply, D6: self power supply, D5: remote wake-up
*/
#define USB_CDC_DESC_CFG_POWER_MODE (0x01 << 7)
/**
* usb cdc use endpoint define
*/
#ifdef PM5
#define USB_CDC_DESC_INT_EPT 0x82
#define USB_CDC_DESC_BULK_IN_EPT 0x81
#define USB_CDC_DESC_BULK_OUT_EPT 0x01
#else
#define USB_CDC_DESC_INT_EPT 0x83
#define USB_CDC_DESC_BULK_IN_EPT 0x82
#define USB_CDC_DESC_BULK_OUT_EPT 0x01
#endif
/**
* endpoint buffer size
*/
#ifdef PM5
#define USB_CDC_DESC_MAX_EP0_SIZE 64
#define USB_CDC_DESC_IN_PACKET_SIZE 0x40
#define USB_CDC_DESC_OUT_PACKET_SIZE 0x40
#else
#define USB_CDC_DESC_MAX_EP0_SIZE 8
#define USB_CDC_DESC_IN_PACKET_SIZE 0x40
#define USB_CDC_DESC_OUT_PACKET_SIZE 0x40
#endif
// Fixed value. To support WCID, the device needs to respond to a special string descriptor request and return a special character descriptor.
// The Windows system will initiate a manufacturer customized request to obtain the WCID of the device based on the parameters in this character descriptor.
// After obtaining the WCID, match and install the driver based on the WCID./
// NOTE: There are no special specifications, so the relevant definitions cannot be found on the Internet.
// https://www.usbzh.com/article/detail-625.html
#define USB_CDC_DESC_MS_VENDOR_CODE 0x1C
// exported all desc.
extern const char devDescriptor[18];
extern const char cfgDescriptor[67];
extern const char bosDescriptor[12];
extern const char StrLanguageCodes[4];
extern const char StrManufacturer[26];
extern const char StrProduct[20];
// If the device has FLASH, the USB serial number is dynamically generated(NOT const).
#ifndef WITH_FLASH
extern const char StrSerialNumber[14];
#else
extern char StrSerialNumber[50];
#endif
// WCID, for DRIVER auto install on windows platform.
// DOCS: https://www.usbzh.com/article/detail-625.html
extern const char StrMS_OSDescriptor[18];
#endif
+97
View File
@@ -0,0 +1,97 @@
#include "string.h"
#include "usb_read_ng.h"
static const usb_read_ng_config_t *g_config = NULL;
static size_t g_buf_len = 0;
static size_t g_buf_offset = 0;
#ifndef MIN
#define MIN(a, b) ((a) < (b) ? (a) : (b))
#endif
void usb_read_ng_init(const usb_read_ng_config_t *config)
{
if (!config || !config->is_link_ready || !config->is_data_ready ||
!config->get_byte_count || !config->read_fifo ||
!config->clear_ready || !config->buffer || config->buffer_size == 0) {
return;
}
g_config = config;
g_buf_len = 0;
g_buf_offset = 0;
}
bool usb_read_ng_has_buffered_data(void)
{
return g_buf_len > 0;
}
uint32_t usb_read_ng(uint8_t *data, size_t len)
{
if (!g_config || !data || len == 0) {
return 0;
}
uint32_t nbBytesRcv = 0;
uint16_t time_out = 0;
const uint16_t timeout_limit = g_config->timeout; // Timeout value of platform
// First from buffer of this module.
if (len <= g_buf_len) {
memcpy(data, g_config->buffer + g_buf_offset, len);
g_buf_len -= len;
g_buf_offset = g_buf_len ? g_buf_offset + len : 0;
return len;
}
if (g_buf_len > 0) {
memcpy(data, g_config->buffer + g_buf_offset, g_buf_len);
nbBytesRcv = g_buf_len;
len -= g_buf_len;
g_buf_len = 0;
g_buf_offset = 0;
}
while (len > 0) {
// 1. if usb status is disconnected or unopened, exit read for device side.
if (!g_config->is_link_ready()) {
break;
}
// 2. check if data ready for usb device, if not, skip read and check timeout.
if (g_config->is_data_ready()) {
uint16_t available = g_config->get_byte_count();
uint16_t packetSize = MIN(available, len);
for (uint16_t i = 0; i < packetSize; i++) {
data[nbBytesRcv++] = g_config->read_fifo(); // read from device fifo.
}
available -= packetSize;
len -= packetSize;
size_t to_buffer = (available < g_config->buffer_size) ? available : g_config->buffer_size;
for (size_t i = 0; i < to_buffer; i++) {
g_config->buffer[i] = g_config->read_fifo();
}
g_buf_len = to_buffer;
g_buf_offset = 0;
// gc gc gc gc !!!
g_config->clear_ready();
time_out = 0; // Timeout reset.
}
else {
// usb link ready but no data. to check simple timeout.
if (timeout_limit > 0) {
time_out++;
if (time_out >= timeout_limit) {
break; // exit if timeout.
}
} else {
break; // no timeout. exit immediately.
}
}
}
return nbBytesRcv;
}
+52
View File
@@ -0,0 +1,52 @@
#ifndef USB_READ_NG_H
#define USB_READ_NG_H
#include <stdint.h>
#include <stdbool.h>
#include <stddef.h>
// --------------------- HAL BY DXL ---------------------
// We need to consider whether it will affect the reading performance of USB in order to optimize it.
// The HAL layer should not contain any code related the platform.
#ifdef __cplusplus
extern "C" {
#endif
// Callbacks, implement functions on platform related.
typedef bool (*usb_link_ready_cb_t)(void); // is usb link ready?
typedef bool (*usb_data_ready_cb_t)(void); // is data received ready?
typedef uint16_t (*usb_get_byte_count_cb_t)(void); // how length of data received?
typedef uint8_t (*usb_read_fifo_cb_t)(void); // read byte from fifo
typedef void (*usb_clear_rx_ready_cb_t)(void); // clear
// Configs, instance of platform.
typedef struct {
usb_link_ready_cb_t is_link_ready;
usb_data_ready_cb_t is_data_ready;
usb_get_byte_count_cb_t get_byte_count;
usb_read_fifo_cb_t read_fifo;
usb_clear_rx_ready_cb_t clear_ready;
uint8_t *buffer; // buffer for read ng of platform.
size_t buffer_size; // buffer size
uint16_t timeout; // read timeout if no data ready.
} usb_read_ng_config_t;
// setup usb read ng, implement all usb related function for platform.
// @param: config - the module will use this point on global, so don't instance in function stack!
void usb_read_ng_init(const usb_read_ng_config_t *config);
// exported api, not platform related, for check data available of local usb ng buffer(not usb ep buffer)
// nonblocking api
bool usb_read_ng_has_buffered_data(void);
// exported api, not platform related, for read data from local buffer or usb device online.
// nonblocking api
uint32_t usb_read_ng(uint8_t *data, size_t len);
#ifdef __cplusplus
}
#endif
#endif