diff options
author | Raghuram Subramani <raghus2247@gmail.com> | 2022-06-19 19:47:51 +0530 |
---|---|---|
committer | Raghuram Subramani <raghus2247@gmail.com> | 2022-06-19 19:47:51 +0530 |
commit | 4fd287655a72b9aea14cdac715ad5b90ed082ed2 (patch) | |
tree | 65d393bc0e699dd12d05b29ba568e04cea666207 /circuitpython/supervisor/shared/usb | |
parent | 0150f70ce9c39e9e6dd878766c0620c85e47bed0 (diff) |
add circuitpython code
Diffstat (limited to 'circuitpython/supervisor/shared/usb')
-rw-r--r-- | circuitpython/supervisor/shared/usb/tusb_config.h | 167 | ||||
-rw-r--r-- | circuitpython/supervisor/shared/usb/usb.c | 321 | ||||
-rw-r--r-- | circuitpython/supervisor/shared/usb/usb_desc.c | 365 | ||||
-rw-r--r-- | circuitpython/supervisor/shared/usb/usb_msc_flash.c | 287 | ||||
-rw-r--r-- | circuitpython/supervisor/shared/usb/usb_vendor_descriptors.h | 39 |
5 files changed, 1179 insertions, 0 deletions
diff --git a/circuitpython/supervisor/shared/usb/tusb_config.h b/circuitpython/supervisor/shared/usb/tusb_config.h new file mode 100644 index 0000000..13b4367 --- /dev/null +++ b/circuitpython/supervisor/shared/usb/tusb_config.h @@ -0,0 +1,167 @@ +/**************************************************************************/ +/*! + @file tusb_config.h + @author hathach (tinyusb.org) + + @section LICENSE + + Software License Agreement (BSD License) + + Copyright (c) 2013, hathach (tinyusb.org) + All rights reserved. + + Redistribution and use in source and binary forms, with or without + modification, are permitted provided that the following conditions are met: + 1. Redistributions of source code must retain the above copyright + notice, this list of conditions and the following disclaimer. + 2. Redistributions in binary form must reproduce the above copyright + notice, this list of conditions and the following disclaimer in the + documentation and/or other materials provided with the distribution. + 3. Neither the name of the copyright holders nor the + names of its contributors may be used to endorse or promote products + derived from this software without specific prior written permission. + + THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ''AS IS'' AND ANY + EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED + WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE + DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER BE LIABLE FOR ANY + DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES + INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; + LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION HOWEVER CAUSED AND + ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT + INCLUDING NEGLIGENCE OR OTHERWISE ARISING IN ANY WAY OUT OF THE USE OF THIS + SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + +*/ +/**************************************************************************/ + +#ifndef _TUSB_CONFIG_H_ +#define _TUSB_CONFIG_H_ + +#include "py/mpconfig.h" + +#ifdef __cplusplus +extern "C" { +#endif + +// --------------------------------------------------------------------+ +// COMMON CONFIGURATION +// --------------------------------------------------------------------+ + +// When debugging TinyUSB, only output to the UART debug link. +#if CIRCUITPY_DEBUG_TINYUSB > 0 && defined(CIRCUITPY_DEBUG_UART_TX) +#define CFG_TUSB_DEBUG CIRCUITPY_DEBUG_TINYUSB +#define CFG_TUSB_DEBUG_PRINTF debug_uart_printf +#endif + +/*------------- RTOS -------------*/ +#ifndef CFG_TUSB_OS +#define CFG_TUSB_OS OPT_OS_NONE +#endif +// #define CFG_TUD_TASK_QUEUE_SZ 16 + +// --------------------------------------------------------------------+ +// DEVICE CONFIGURATION +// --------------------------------------------------------------------+ + +#if CIRCUITPY_USB_DEVICE_INSTANCE == 0 +#if USB_HIGHSPEED +#define CFG_TUSB_RHPORT0_MODE (OPT_MODE_DEVICE | OPT_MODE_HIGH_SPEED) +#else +#define CFG_TUSB_RHPORT0_MODE (OPT_MODE_DEVICE) +#endif +#elif CIRCUITPY_USB_DEVICE_INSTANCE == 1 +#if USB_HIGHSPEED +#define CFG_TUSB_RHPORT1_MODE (OPT_MODE_DEVICE | OPT_MODE_HIGH_SPEED) +#else +#define CFG_TUSB_RHPORT1_MODE (OPT_MODE_DEVICE) +#endif +#endif + +// Vendor name included in Inquiry response, max 8 bytes +#define CFG_TUD_MSC_VENDOR USB_MANUFACTURER_8 + +// Product name included in Inquiry response, max 16 bytes +#define CFG_TUD_MSC_PRODUCT USB_PRODUCT_16 +#define CFG_TUD_ENDPOINT0_SIZE 64 + +// ------------- CLASS -------------// + +// Will be set to 2 in supervisor.mk if CIRCUITPY_USB_CDC is set. +#ifndef CFG_TUD_CDC +#define CFG_TUD_CDC 1 +#endif + +#define CFG_TUD_MSC CIRCUITPY_USB_MSC +#define CFG_TUD_HID CIRCUITPY_USB_HID +#define CFG_TUD_MIDI CIRCUITPY_USB_MIDI +#define CFG_TUD_VENDOR CIRCUITPY_USB_VENDOR +#define CFG_TUD_CUSTOM_CLASS 0 + +/*------------------------------------------------------------------*/ +/* CLASS DRIVER + *------------------------------------------------------------------*/ + +// Product revision string included in Inquiry response, max 4 bytes +#define CFG_TUD_MSC_PRODUCT_REV "1.0" + + +// --------------------------------------------------------------------+ +// USB RAM PLACEMENT +// --------------------------------------------------------------------+ +#if !defined(CIRCUITPY_TUSB_ATTR_USBRAM) +#define CIRCUITPY_TUSB_ATTR_USBRAM ".bss.usbram" +#endif + +#define CFG_TUSB_ATTR_USBRAM __attribute__((section(CIRCUITPY_TUSB_ATTR_USBRAM))) + + +#if !defined(CIRCUITPY_TUSB_MEM_ALIGN) +#define CIRCUITPY_TUSB_MEM_ALIGN 4 +#endif + +#define CFG_TUSB_MEM_ALIGN __attribute__ ((aligned(CIRCUITPY_TUSB_MEM_ALIGN))) + +// -------------------------------------------------------------------- +// HOST CONFIGURATION +// -------------------------------------------------------------------- + +#if CIRCUITPY_USB_HOST + +#if CIRCUITPY_USB_HOST_INSTANCE == 0 +#if USB_HIGHSPEED +#define CFG_TUSB_RHPORT0_MODE (OPT_MODE_HOST | OPT_MODE_HIGH_SPEED) +#else +#define CFG_TUSB_RHPORT0_MODE (OPT_MODE_HOST) +#endif +#elif CIRCUITPY_USB_HOST_INSTANCE == 1 +#if USB_HIGHSPEED +#define CFG_TUSB_RHPORT1_MODE (OPT_MODE_HOST | OPT_MODE_HIGH_SPEED) +#else +#define CFG_TUSB_RHPORT1_MODE (OPT_MODE_HOST) +#endif +#endif + +// Size of buffer to hold descriptors and other data used for enumeration +#ifndef CFG_TUH_ENUMERATION_BUFSIZE +#define CFG_TUH_ENUMERATION_BUFSIZE 256 +#endif + +#define CFG_TUH_HUB 1 +#define CFG_TUH_CDC 0 +#define CFG_TUH_MSC 0 +#define CFG_TUH_VENDOR 0 + +// max device support (excluding hub device) +#define CFG_TUH_DEVICE_MAX (CFG_TUH_HUB ? 4 : 1) // hub typically has 4 ports + +// Number of endpoints per device +#define CFG_TUH_ENDPOINT_MAX 8 + +#endif + +#ifdef __cplusplus +} +#endif + +#endif /* _TUSB_CONFIG_H_ */ diff --git a/circuitpython/supervisor/shared/usb/usb.c b/circuitpython/supervisor/shared/usb/usb.c new file mode 100644 index 0000000..a188544 --- /dev/null +++ b/circuitpython/supervisor/shared/usb/usb.c @@ -0,0 +1,321 @@ +/* + * This file is part of the Micro Python project, http://micropython.org/ + * + * The MIT License (MIT) + * + * Copyright (c) 2018 hathach for Adafruit Industries + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + * THE SOFTWARE. + */ + +#include "py/objstr.h" +#include "py/runtime.h" +#include "shared-bindings/microcontroller/Processor.h" +#include "supervisor/background_callback.h" +#include "supervisor/port.h" +#include "supervisor/serial.h" +#include "supervisor/usb.h" +#include "supervisor/shared/workflow.h" +#include "shared/runtime/interrupt_char.h" +#include "shared/readline/readline.h" + +#if CIRCUITPY_STORAGE +#include "shared-module/storage/__init__.h" +#endif + +#if CIRCUITPY_USB_CDC +#include "shared-module/usb_cdc/__init__.h" +#endif + +#if CIRCUITPY_USB_HID +#include "shared-module/usb_hid/__init__.h" +#endif + +#if CIRCUITPY_USB_MIDI +#include "shared-module/usb_midi/__init__.h" +#endif + +#include "tusb.h" + +#if CIRCUITPY_USB_VENDOR +#include "usb_vendor_descriptors.h" + +// The WebUSB support being conditionally added to this file is based on the +// tinyusb demo examples/device/webusb_serial. + +static bool web_serial_connected = false; + +#define URL "www.tinyusb.org/examples/webusb-serial" + +const tusb_desc_webusb_url_t desc_webusb_url = +{ + .bLength = 3 + sizeof(URL) - 1, + .bDescriptorType = 3, // WEBUSB URL type + .bScheme = 1, // 0: http, 1: https + .url = URL +}; + +#endif + +bool usb_enabled(void) { + return tusb_inited(); +} + +MP_WEAK void post_usb_init(void) { +} + +void usb_init(void) { + init_usb_hardware(); + + tusb_init(); + + post_usb_init(); + + #if MICROPY_KBD_EXCEPTION && CIRCUITPY_USB_CDC + // Set Ctrl+C as wanted char, tud_cdc_rx_wanted_cb() usb_callback will be invoked when Ctrl+C is received + // This usb_callback always got invoked regardless of mp_interrupt_char value since we only set it once here + + // Don't watch for ctrl-C if there is no REPL. + if (usb_cdc_console_enabled()) { + // Console will always be itf 0. + tud_cdc_set_wanted_char(CHAR_CTRL_C); + } + #endif +} + +// Set up USB defaults before any USB changes are made in boot.py +void usb_set_defaults(void) { + #if CIRCUITPY_STORAGE && CIRCUITPY_USB_MSC + storage_usb_set_defaults(); + #endif + + #if CIRCUITPY_USB_CDC + usb_cdc_set_defaults(); + #endif + + #if CIRCUITPY_USB_HID + usb_hid_set_defaults(); + #endif + + #if CIRCUITPY_USB_MIDI + usb_midi_set_defaults(); + #endif +}; + +// Some dynamic USB data must be saved after boot.py. How much is needed? +size_t usb_boot_py_data_size(void) { + size_t size = 0; + + #if CIRCUITPY_USB_HID + size += usb_hid_report_descriptor_length(); + #endif + + return size; +} + +// Fill in the data to save. +void usb_get_boot_py_data(uint8_t *temp_storage, size_t temp_storage_size) { + #if CIRCUITPY_USB_HID + usb_hid_build_report_descriptor(temp_storage, temp_storage_size); + #endif +} + +// After VM is gone, save data into non-heap storage (storage_allocations). +void usb_return_boot_py_data(uint8_t *temp_storage, size_t temp_storage_size) { + #if CIRCUITPY_USB_HID + usb_hid_save_report_descriptor(temp_storage, temp_storage_size); + #endif + + // Now we can also build the rest of the descriptors and place them in storage_allocations. + usb_build_descriptors(); +} + +// Call this when ready to run code.py or a REPL, and a VM has been started. +void usb_setup_with_vm(void) { + #if CIRCUITPY_USB_HID + usb_hid_setup_devices(); + #endif + + #if CIRCUITPY_USB_MIDI + usb_midi_setup_ports(); + #endif +} + +void usb_disconnect(void) { + tud_disconnect(); +} + +void usb_background(void) { + if (usb_enabled()) { + #if CFG_TUSB_OS == OPT_OS_NONE + tud_task(); + #if CIRCUITPY_USB_HOST + tuh_task(); + #endif + #endif + // No need to flush if there's no REPL. + #if CIRCUITPY_USB_CDC + if (usb_cdc_console_enabled()) { + // Console will always be itf 0. + tud_cdc_write_flush(); + } + #endif + } +} + +static background_callback_t usb_callback; +static void usb_background_do(void *unused) { + usb_background(); +} + +void usb_background_schedule(void) { + background_callback_add(&usb_callback, usb_background_do, NULL); +} + +void usb_irq_handler(int instance) { + if (instance == CIRCUITPY_USB_DEVICE_INSTANCE) { + tud_int_handler(instance); + } else if (instance == CIRCUITPY_USB_HOST_INSTANCE) { + #if CIRCUITPY_USB_HOST + tuh_int_handler(instance); + #endif + } + + usb_background_schedule(); +} + +// --------------------------------------------------------------------+ +// tinyusb callbacks +// --------------------------------------------------------------------+ + +// Invoked when device is mounted +void tud_mount_cb(void) { + #if CIRCUITPY_USB_MSC + usb_msc_mount(); + #endif +} + +// Invoked when device is unmounted +void tud_umount_cb(void) { + #if CIRCUITPY_USB_MSC + usb_msc_umount(); + #endif +} + +// Invoked when usb bus is suspended +// remote_wakeup_en : if host allows us to perform remote wakeup +// USB Specs: Within 7ms, device must draw an average current less than 2.5 mA from bus +void tud_suspend_cb(bool remote_wakeup_en) { +} + +// Invoked when usb bus is resumed +void tud_resume_cb(void) { +} + +// Invoked when cdc when line state changed e.g connected/disconnected +// Use to reset to DFU when disconnect with 1200 bps +void tud_cdc_line_state_cb(uint8_t itf, bool dtr, bool rts) { + (void)itf; // interface ID, not used + + // DTR = false is counted as disconnected + if (!dtr) { + cdc_line_coding_t coding; + // Use whichever CDC is itf 0. + tud_cdc_get_line_coding(&coding); + + if (coding.bit_rate == 1200) { + reset_to_bootloader(); + } + } +} + +#if CIRCUITPY_USB_VENDOR +// --------------------------------------------------------------------+ +// WebUSB use vendor class +// --------------------------------------------------------------------+ + +bool tud_vendor_connected(void) { + return web_serial_connected; +} + +// Invoked when a control transfer occurred on an interface of this class +// Driver response accordingly to the request and the transfer stage (setup/data/ack) +// return false to stall control endpoint (e.g unsupported request) +bool tud_vendor_control_xfer_cb(uint8_t rhport, uint8_t stage, tusb_control_request_t const *request) { + // nothing to with DATA & ACK stage + if (stage != CONTROL_STAGE_SETUP) { + return true; + } + + switch (request->bRequest) + { + case VENDOR_REQUEST_WEBUSB: + // match vendor request in BOS descriptor + // Get landing page url + return tud_control_xfer(rhport, request, (void *)&desc_webusb_url, desc_webusb_url.bLength); + + case VENDOR_REQUEST_MICROSOFT: + if (request->wIndex == 7) { + // Get Microsoft OS 2.0 compatible descriptor + // let's just hope the target architecture always has the same endianness + uint16_t total_len; + memcpy(&total_len, vendor_ms_os_20_descriptor() + 8, 2); + + return tud_control_xfer(rhport, request, (void *)vendor_ms_os_20_descriptor(), total_len); + } else { + return false; + } + + case 0x22: + // Webserial simulate the CDC_REQUEST_SET_CONTROL_LINE_STATE (0x22) to + // connect and disconnect. + web_serial_connected = (request->wValue != 0); + + // response with status OK + return tud_control_status(rhport, request); + + default: + // stall unknown request + return false; + } + + return true; +} +#endif // CIRCUITPY_USB_VENDOR + + +#if MICROPY_KBD_EXCEPTION + +/** + * Callback invoked when received an "wanted" char. + * @param itf Interface index (for multiple cdc interfaces) + * @param wanted_char The wanted char (set previously) + */ + +// Only called when console is enabled. +void tud_cdc_rx_wanted_cb(uint8_t itf, char wanted_char) { + // Workaround for using shared/runtime/interrupt_char.c + // Compare mp_interrupt_char with wanted_char and ignore if not matched + if (mp_interrupt_char == wanted_char) { + tud_cdc_n_read_flush(itf); // flush read fifo + mp_sched_keyboard_interrupt(); + } +} + +#endif diff --git a/circuitpython/supervisor/shared/usb/usb_desc.c b/circuitpython/supervisor/shared/usb/usb_desc.c new file mode 100644 index 0000000..9fe1ead --- /dev/null +++ b/circuitpython/supervisor/shared/usb/usb_desc.c @@ -0,0 +1,365 @@ +/* + * This file is part of the MicroPython project, http://micropython.org/ + * + * The MIT License (MIT) + * + * Copyright (c) 2018 hathach for Adafruit Industries + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + * THE SOFTWARE. + */ + +#include "lib/tinyusb/src/tusb.h" + +#include "py/objstr.h" +#include "py/runtime.h" +#include "supervisor/memory.h" +#include "supervisor/shared/safe_mode.h" +#include "supervisor/usb.h" + +#if CIRCUITPY_USB_CDC +#include "shared-bindings/usb_cdc/__init__.h" +#endif + +#if CIRCUITPY_USB_HID +#include "shared-bindings/usb_hid/__init__.h" +#endif + +#if CIRCUITPY_USB_MIDI +#include "shared-bindings/usb_midi/__init__.h" +#endif + +#if CIRCUITPY_USB_MSC && CIRCUITPY_STORAGE +#include "shared-bindings/storage/__init__.h" +#endif + +#include "shared-bindings/microcontroller/Processor.h" + + +// Table for collecting interface strings (interface names) as descriptor is built. +// We reuse the same table after collection, replacing the char string pointers with le16 string pointers. +#define MAX_INTERFACE_STRINGS 16 +// slot 0 is always the Language ID +typedef union { + const char *char_str; + const uint16_t *descriptor; +} interface_string_t; +static interface_string_t collected_interface_strings[MAX_INTERFACE_STRINGS]; + +static size_t collected_interface_strings_length; +static uint8_t current_interface_string; + +static supervisor_allocation *device_descriptor_allocation; +static supervisor_allocation *configuration_descriptor_allocation; +static supervisor_allocation *string_descriptors_allocation; + +static const char manufacturer_name[] = USB_MANUFACTURER; +static const char product_name[] = USB_PRODUCT; + +// Serial number string is UID length * 2 (2 nibbles per byte) + 1 byte for null termination. +static char serial_number_hex_string[COMMON_HAL_MCU_PROCESSOR_UID_LENGTH * 2 + 1]; + + +static const uint8_t device_descriptor_template[] = { + 0x12, // 0 bLength + 0x01, // 1 bDescriptorType (Device) + 0x00, 0x02, // 2,3 bcdUSB 2.00 + 0x00, // 4 bDeviceClass (Use class information in the Interface Descriptors) + 0x00, // 5 bDeviceSubClass + 0x00, // 6 bDeviceProtocol + 0x40, // 7 bMaxPacketSize0 64 + 0xFF, 0xFF, // 8,9 idVendor [SET AT RUNTIME: lo,hi] +#define DEVICE_VID_LO_INDEX (8) +#define DEVICE_VID_HI_INDEX (9) + 0xFF, 0xFF, // 10,11 idProduct [SET AT RUNTIME: lo,hi] +#define DEVICE_PID_LO_INDEX (10) +#define DEVICE_PID_HI_INDEX (11) + 0x00, 0x01, // 12,13 bcdDevice 2.00 + 0xFF, // 14 iManufacturer (String Index) [SET AT RUNTIME] +#define DEVICE_MANUFACTURER_STRING_INDEX (14) + 0xFF, // 15 iProduct (String Index) [SET AT RUNTIME] +#define DEVICE_PRODUCT_STRING_INDEX (15) + 0xFF, // 16 iSerialNumber (String Index) [SET AT RUNTIME] +#define DEVICE_SERIAL_NUMBER_STRING_INDEX (16) + 0x01, // 17 bNumConfigurations 1 +}; + +static const uint8_t configuration_descriptor_template[] = { + 0x09, // 0 bLength + 0x02, // 1 bDescriptorType (Configuration) + 0xFF, 0xFF, // 2,3 wTotalLength [SET AT RUNTIME: lo, hi] +#define CONFIG_TOTAL_LENGTH_LO_INDEX (2) +#define CONFIG_TOTAL_LENGTH_HI_INDEX (3) + 0xFF, // 4 bNumInterfaces [SET AT RUNTIME] +#define CONFIG_NUM_INTERFACES_INDEX (4) + 0x01, // 5 bConfigurationValue + 0x00, // 6 iConfiguration (String Index) + 0x80, // 7 bmAttributes + 0x32, // 8 bMaxPower 100mA +}; + +static void usb_build_device_descriptor(uint16_t vid, uint16_t pid) { + device_descriptor_allocation = + allocate_memory(align32_size(sizeof(device_descriptor_template)), + /*high_address*/ false, /*movable*/ false); + uint8_t *device_descriptor = (uint8_t *)device_descriptor_allocation->ptr; + memcpy(device_descriptor, device_descriptor_template, sizeof(device_descriptor_template)); + + device_descriptor[DEVICE_VID_LO_INDEX] = vid & 0xFF; + device_descriptor[DEVICE_VID_HI_INDEX] = vid >> 8; + device_descriptor[DEVICE_PID_LO_INDEX] = pid & 0xFF; + device_descriptor[DEVICE_PID_HI_INDEX] = pid >> 8; + + usb_add_interface_string(current_interface_string, manufacturer_name); + device_descriptor[DEVICE_MANUFACTURER_STRING_INDEX] = current_interface_string; + current_interface_string++; + + usb_add_interface_string(current_interface_string, product_name); + device_descriptor[DEVICE_PRODUCT_STRING_INDEX] = current_interface_string; + current_interface_string++; + + usb_add_interface_string(current_interface_string, serial_number_hex_string); + device_descriptor[DEVICE_SERIAL_NUMBER_STRING_INDEX] = current_interface_string; + current_interface_string++; +} + +static void usb_build_configuration_descriptor(void) { + size_t total_descriptor_length = sizeof(configuration_descriptor_template); + + // CDC should be first, for compatibility with Adafruit Windows 7 drivers. + // In the past, the order has been CDC, MSC, MIDI, HID, so preserve that order. + #if CIRCUITPY_USB_CDC + if (usb_cdc_console_enabled()) { + total_descriptor_length += usb_cdc_descriptor_length(); + } + if (usb_cdc_data_enabled()) { + total_descriptor_length += usb_cdc_descriptor_length(); + } + #endif + + #if CIRCUITPY_USB_MSC + if (storage_usb_enabled()) { + total_descriptor_length += storage_usb_descriptor_length(); + } + #endif + + #if CIRCUITPY_USB_HID + if (usb_hid_enabled()) { + total_descriptor_length += usb_hid_descriptor_length(); + } + #endif + + #if CIRCUITPY_USB_MIDI + if (usb_midi_enabled()) { + total_descriptor_length += usb_midi_descriptor_length(); + } + #endif + + #if CIRCUITPY_USB_VENDOR + if (usb_vendor_enabled()) { + total_descriptor_length += usb_vendor_descriptor_length(); + } + #endif + + + // Now we now how big the configuration descriptor will be, so we can allocate space for it. + configuration_descriptor_allocation = + allocate_memory(align32_size(total_descriptor_length), + /*high_address*/ false, /*movable*/ false); + uint8_t *configuration_descriptor = (uint8_t *)configuration_descriptor_allocation->ptr; + + // Copy the template, which is the first part of the descriptor, and fix up its length. + + memcpy(configuration_descriptor, configuration_descriptor_template, sizeof(configuration_descriptor_template)); + + configuration_descriptor[CONFIG_TOTAL_LENGTH_LO_INDEX] = total_descriptor_length & 0xFF; + configuration_descriptor[CONFIG_TOTAL_LENGTH_HI_INDEX] = (total_descriptor_length >> 8) & 0xFF; + + // Number interfaces and endpoints. + // Endpoint 0 is already used for USB control, + // so start with 1 for the current endpoint and for the number of in and out endpoints + // already in use. + + descriptor_counts_t descriptor_counts = { + .current_interface = 0, + .current_endpoint = 1, + .num_in_endpoints = 1, + .num_out_endpoints = 1, + }; + + uint8_t *descriptor_buf_remaining = configuration_descriptor + sizeof(configuration_descriptor_template); + + #if CIRCUITPY_USB_CDC + if (usb_cdc_console_enabled()) { + // Concatenate and fix up the CDC REPL descriptor. + descriptor_buf_remaining += usb_cdc_add_descriptor( + descriptor_buf_remaining, &descriptor_counts, ¤t_interface_string, true /*console*/); + + } + if (usb_cdc_data_enabled()) { + // Concatenate and fix up the CDC data descriptor. + descriptor_buf_remaining += usb_cdc_add_descriptor( + descriptor_buf_remaining, &descriptor_counts, ¤t_interface_string, false /*console*/); + } + #endif + + #if CIRCUITPY_USB_MSC + if (storage_usb_enabled()) { + // Concatenate and fix up the MSC descriptor. + descriptor_buf_remaining += storage_usb_add_descriptor( + descriptor_buf_remaining, &descriptor_counts, ¤t_interface_string); + } + #endif + + #if CIRCUITPY_USB_HID + if (usb_hid_enabled()) { + if (usb_hid_boot_device() > 0 && descriptor_counts.current_interface > 0) { + // Hosts using boot devices generally to expect them to be at interface zero, + // and will not work properly otherwise. + reset_into_safe_mode(USB_BOOT_DEVICE_NOT_INTERFACE_ZERO); + } + descriptor_buf_remaining += usb_hid_add_descriptor( + descriptor_buf_remaining, &descriptor_counts, ¤t_interface_string, + usb_hid_report_descriptor_length(), usb_hid_boot_device()); + } + #endif + + #if CIRCUITPY_USB_MIDI + if (usb_midi_enabled()) { + // Concatenate and fix up the MIDI descriptor. + descriptor_buf_remaining += usb_midi_add_descriptor( + descriptor_buf_remaining, &descriptor_counts, ¤t_interface_string); + } + #endif + + #if CIRCUITPY_USB_VENDOR + if (usb_vendor_enabled()) { + descriptor_buf_remaining += usb_vendor_add_descriptor( + descriptor_buf_remaining, &descriptor_counts, ¤t_interface_string); + } + #endif + + // Now we know how many interfaces have been used. + configuration_descriptor[CONFIG_NUM_INTERFACES_INDEX] = descriptor_counts.current_interface; + + // Did we run out of endpoints? + if (descriptor_counts.current_endpoint > USB_NUM_ENDPOINT_PAIRS || + descriptor_counts.num_in_endpoints > USB_NUM_IN_ENDPOINTS || + descriptor_counts.num_out_endpoints > USB_NUM_OUT_ENDPOINTS) { + reset_into_safe_mode(USB_TOO_MANY_ENDPOINTS); + } +} + +// str must not be on the heap. +void usb_add_interface_string(uint8_t interface_string_index, const char str[]) { + if (interface_string_index > MAX_INTERFACE_STRINGS) { + reset_into_safe_mode(USB_TOO_MANY_INTERFACE_NAMES); + } + + collected_interface_strings[interface_string_index].char_str = str; + collected_interface_strings_length += strlen(str); +} + +static const uint16_t language_id[] = { + 0x0304, + 0x0409, +}; + +static void usb_build_interface_string_table(void) { + // Allocate space for the le16 String descriptors. + // Space needed is 2 bytes for String Descriptor header, then 2 bytes for each character + string_descriptors_allocation = + allocate_memory(align32_size(current_interface_string * 2 + collected_interface_strings_length * 2), + /*high_address*/ false, /*movable*/ false); + uint16_t *string_descriptors = (uint16_t *)string_descriptors_allocation->ptr; + + + uint16_t *string_descriptor = string_descriptors; + + // Language ID is always the 0th string descriptor. + collected_interface_strings[0].descriptor = language_id; + + // Build the le16 versions of all the descriptor strings. + // Start at 1 to skip the Language ID. + for (uint8_t string_index = 1; string_index < current_interface_string; string_index++) { + const char *str = collected_interface_strings[string_index].char_str; + const size_t str_len = strlen(str); + // 1 word for descriptor type and length, 1 word for each character. + const uint8_t descriptor_size_words = 1 + str_len; + const uint8_t descriptor_size_bytes = descriptor_size_words * 2; + string_descriptor[0] = 0x0300 | descriptor_size_bytes; + + // Convert to le16. + for (size_t i = 0; i < str_len; i++) { + string_descriptor[i + 1] = str[i]; + } + + // Save ptr to string descriptor with le16 str. + collected_interface_strings[string_index].descriptor = string_descriptor; + + // Move to next descriptor slot. + string_descriptor += descriptor_size_words; + } +} + +// After boot.py runs, the USB devices to be used have been chosen, and the descriptors can be set up. +// This is called after the VM is finished, because it uses storage_allocations. +void usb_build_descriptors(void) { + uint8_t raw_id[COMMON_HAL_MCU_PROCESSOR_UID_LENGTH]; + common_hal_mcu_processor_get_uid(raw_id); + + for (int i = 0; i < COMMON_HAL_MCU_PROCESSOR_UID_LENGTH; i++) { + for (int j = 0; j < 2; j++) { + uint8_t nibble = (raw_id[i] >> (j * 4)) & 0xf; + serial_number_hex_string[i * 2 + (1 - j)] = nibble_to_hex_upper[nibble]; + } + } + + // Null-terminate the string. + serial_number_hex_string[sizeof(serial_number_hex_string) - 1] = '\0'; + + current_interface_string = 1; + collected_interface_strings_length = 0; + + usb_build_device_descriptor(USB_VID, USB_PID); + usb_build_configuration_descriptor(); + usb_build_interface_string_table(); +} + +// Invoked when GET DEVICE DESCRIPTOR is received. +// Application return pointer to descriptor +uint8_t const *tud_descriptor_device_cb(void) { + return (uint8_t *)device_descriptor_allocation->ptr; +} + +// Invoked when GET CONFIGURATION DESCRIPTOR is received. +// Application return pointer to descriptor +// Descriptor contents must exist long enough for transfer to complete +uint8_t const *tud_descriptor_configuration_cb(uint8_t index) { + (void)index; // for multiple configurations + return (uint8_t *)configuration_descriptor_allocation->ptr; +} + +// Invoked when GET STRING DESCRIPTOR request is received. +// Application return pointer to descriptor, whose contents must exist long enough for transfer to complete +uint16_t const *tud_descriptor_string_cb(uint8_t index, uint16_t langid) { + if (index > MAX_INTERFACE_STRINGS) { + return NULL; + } + return collected_interface_strings[index].descriptor; +} diff --git a/circuitpython/supervisor/shared/usb/usb_msc_flash.c b/circuitpython/supervisor/shared/usb/usb_msc_flash.c new file mode 100644 index 0000000..f183033 --- /dev/null +++ b/circuitpython/supervisor/shared/usb/usb_msc_flash.c @@ -0,0 +1,287 @@ +/* + * This file is part of the MicroPython project, http://micropython.org/ + * + * The MIT License (MIT) + * + * Copyright (c) 2018 hathach for Adafruit Industries + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + * THE SOFTWARE. + */ + +#include "tusb.h" +// // #include "supervisor/flash.h" + +// For updating fatfs's cache +#include "extmod/vfs.h" +#include "extmod/vfs_fat.h" +#include "lib/oofatfs/diskio.h" +#include "lib/oofatfs/ff.h" +#include "py/mpstate.h" + +#include "shared-module/storage/__init__.h" +#include "supervisor/filesystem.h" +#include "supervisor/shared/reload.h" + +#define MSC_FLASH_BLOCK_SIZE 512 + +static bool ejected[1] = {true}; + +// Lock to track if something else is using the filesystem when USB is plugged in. If so, the drive +// will be made available once the lock is released. +static bool _usb_msc_lock = false; +static bool _usb_connected_while_locked = false; + +STATIC void _usb_msc_uneject(void) { + for (uint8_t i = 0; i < sizeof(ejected); i++) { + ejected[i] = false; + } +} + +void usb_msc_mount(void) { + // Reset the ejection tracking every time we're plugged into USB. This allows for us to battery + // power the device, eject, unplug and plug it back in to get the drive. + if (_usb_msc_lock) { + _usb_connected_while_locked = true; + return; + } + _usb_msc_uneject(); + _usb_connected_while_locked = false; +} + +void usb_msc_umount(void) { +} + +bool usb_msc_ejected(void) { + bool all_ejected = true; + for (uint8_t i = 0; i < sizeof(ejected); i++) { + all_ejected &= ejected[i]; + } + return all_ejected; +} + +bool usb_msc_lock(void) { + if ((storage_usb_enabled() && !usb_msc_ejected()) || _usb_msc_lock) { + return false; + } + _usb_msc_lock = true; + return true; +} + +void usb_msc_unlock(void) { + if (!_usb_msc_lock) { + // Mismatched unlock. + return; + } + if (_usb_connected_while_locked) { + _usb_msc_uneject(); + } + _usb_msc_lock = false; +} + +// The root FS is always at the end of the list. +static fs_user_mount_t *get_vfs(int lun) { + // TODO(tannewt): Return the mount which matches the lun where 0 is the end + // and is counted in reverse. + if (lun > 0) { + return NULL; + } + mp_vfs_mount_t *current_mount = MP_STATE_VM(vfs_mount_table); + if (current_mount == NULL) { + return NULL; + } + while (current_mount->next != NULL) { + current_mount = current_mount->next; + } + return current_mount->obj; +} + +// Callback invoked when received an SCSI command not in built-in list below +// - READ_CAPACITY10, READ_FORMAT_CAPACITY, INQUIRY, TEST_UNIT_READY, START_STOP_UNIT, MODE_SENSE6, REQUEST_SENSE +// - READ10 and WRITE10 have their own callbacks +int32_t tud_msc_scsi_cb(uint8_t lun, const uint8_t scsi_cmd[16], void *buffer, uint16_t bufsize) { + const void *response = NULL; + int32_t resplen = 0; + + switch (scsi_cmd[0]) { + case SCSI_CMD_PREVENT_ALLOW_MEDIUM_REMOVAL: + // Host is about to read/write etc ... better not to disconnect disk + resplen = 0; + break; + + default: + // Set Sense = Invalid Command Operation + tud_msc_set_sense(lun, SCSI_SENSE_ILLEGAL_REQUEST, 0x20, 0x00); + + // negative means error -> tinyusb could stall and/or response with failed status + resplen = -1; + break; + } + + // return len must not larger than bufsize + if (resplen > bufsize) { + resplen = bufsize; + } + + // copy response to stack's buffer if any + if (response && (resplen > 0)) { + memcpy(buffer, response, resplen); + } + + return resplen; +} + +void tud_msc_capacity_cb(uint8_t lun, uint32_t *block_count, uint16_t *block_size) { + fs_user_mount_t *vfs = get_vfs(lun); + disk_ioctl(vfs, GET_SECTOR_COUNT, block_count); + disk_ioctl(vfs, GET_SECTOR_SIZE, block_size); +} + +bool tud_msc_is_writable_cb(uint8_t lun) { + if (lun > 1) { + return false; + } + + fs_user_mount_t *vfs = get_vfs(lun); + if (vfs == NULL) { + return false; + } + if (vfs->blockdev.writeblocks[0] == MP_OBJ_NULL || !filesystem_is_writable_by_usb(vfs)) { + return false; + } + return true; +} + +// Callback invoked when received READ10 command. +// Copy disk's data to buffer (up to bufsize) and return number of copied bytes. +int32_t tud_msc_read10_cb(uint8_t lun, uint32_t lba, uint32_t offset, void *buffer, uint32_t bufsize) { + (void)offset; + + const uint32_t block_count = bufsize / MSC_FLASH_BLOCK_SIZE; + + fs_user_mount_t *vfs = get_vfs(lun); + disk_read(vfs, buffer, lba, block_count); + + return block_count * MSC_FLASH_BLOCK_SIZE; +} + +// Callback invoked when received WRITE10 command. +// Process data in buffer to disk's storage and return number of written bytes +int32_t tud_msc_write10_cb(uint8_t lun, uint32_t lba, uint32_t offset, uint8_t *buffer, uint32_t bufsize) { + (void)lun; + (void)offset; + autoreload_suspend(AUTORELOAD_SUSPEND_USB); + + const uint32_t block_count = bufsize / MSC_FLASH_BLOCK_SIZE; + + fs_user_mount_t *vfs = get_vfs(lun); + disk_write(vfs, buffer, lba, block_count); + // Since by getting here we assume the mount is read-only to + // MicroPython let's update the cached FatFs sector if it's the one + // we just wrote. + #if FF_MAX_SS != FF_MIN_SS + if (vfs->ssize == MSC_FLASH_BLOCK_SIZE) { + #else + // The compiler can optimize this away. + if (FF_MAX_SS == FILESYSTEM_BLOCK_SIZE) { + #endif + if (lba == vfs->fatfs.winsect && lba > 0) { + memcpy(vfs->fatfs.win, + buffer + MSC_FLASH_BLOCK_SIZE * (vfs->fatfs.winsect - lba), + MSC_FLASH_BLOCK_SIZE); + } + } + + return block_count * MSC_FLASH_BLOCK_SIZE; +} + +// Callback invoked when WRITE10 command is completed (status received and accepted by host). +// used to flush any pending cache. +void tud_msc_write10_complete_cb(uint8_t lun) { + (void)lun; + + // This write is complete; initiate an autoreload. + autoreload_resume(AUTORELOAD_SUSPEND_USB); + autoreload_trigger(); +} + +// Invoked when received SCSI_CMD_INQUIRY +// Application fill vendor id, product id and revision with string up to 8, 16, 4 characters respectively +void tud_msc_inquiry_cb(uint8_t lun, uint8_t vendor_id[8], uint8_t product_id[16], uint8_t product_rev[4]) { + (void)lun; + + memcpy(vendor_id, CFG_TUD_MSC_VENDOR, strlen(CFG_TUD_MSC_VENDOR)); + memcpy(product_id, CFG_TUD_MSC_PRODUCT, strlen(CFG_TUD_MSC_PRODUCT)); + memcpy(product_rev, CFG_TUD_MSC_PRODUCT_REV, strlen(CFG_TUD_MSC_PRODUCT_REV)); +} + +// Invoked when received Test Unit Ready command. +// return true allowing host to read/write this LUN e.g SD card inserted +bool tud_msc_test_unit_ready_cb(uint8_t lun) { + if (lun > 1) { + return false; + } + + fs_user_mount_t *current_mount = get_vfs(lun); + if (current_mount == NULL) { + return false; + } + if (ejected[lun]) { + // Set 0x3a for media not present. + tud_msc_set_sense(lun, SCSI_SENSE_NOT_READY, 0x3A, 0x00); + return false; + } + + return true; +} + +// Invoked when received Start Stop Unit command +// - Start = 0 : stopped power mode, if load_eject = 1 : unload disk storage +// - Start = 1 : active mode, if load_eject = 1 : load disk storage +bool tud_msc_start_stop_cb(uint8_t lun, uint8_t power_condition, bool start, bool load_eject) { + if (lun > 1) { + return false; + } + fs_user_mount_t *current_mount = get_vfs(lun); + if (current_mount == NULL) { + return false; + } + if (load_eject) { + if (!start) { + // Eject but first flush. + if (disk_ioctl(current_mount, CTRL_SYNC, NULL) != RES_OK) { + return false; + } else { + ejected[lun] = true; + } + } else { + // We can only load if it hasn't been ejected. + return !ejected[lun]; + } + } else { + if (!start) { + // Stop the unit but don't eject. + if (disk_ioctl(current_mount, CTRL_SYNC, NULL) != RES_OK) { + return false; + } + } + // Always start the unit, even if ejected. Whether media is present is a separate check. + } + + return true; +} diff --git a/circuitpython/supervisor/shared/usb/usb_vendor_descriptors.h b/circuitpython/supervisor/shared/usb/usb_vendor_descriptors.h new file mode 100644 index 0000000..0b41c09 --- /dev/null +++ b/circuitpython/supervisor/shared/usb/usb_vendor_descriptors.h @@ -0,0 +1,39 @@ +/* + * The MIT License (MIT) + * + * Copyright (c) 2019 Ha Thach (tinyusb.org) + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + * THE SOFTWARE. + */ + +#ifndef USB_DESCRIPTORS_H_ +#define USB_DESCRIPTORS_H_ + +#include <stdint.h> + +enum +{ + VENDOR_REQUEST_WEBUSB = 1, + VENDOR_REQUEST_MICROSOFT = 2 +}; + +size_t vendor_ms_os_20_descriptor_length(void); +uint8_t const *vendor_ms_os_20_descriptor(void); + +#endif /* USB_DESCRIPTORS_H_ */ |