diff --git a/mongoose.c b/mongoose.c index 6e41a8c0..1bb15253 100644 --- a/mongoose.c +++ b/mongoose.c @@ -6352,13 +6352,6 @@ size_t mg_l2_eth_trailer(struct mg_tcpip_if *ifp, size_t len, uint8_t *cur) { struct mg_l2addr *mg_l2_eth_mapip(enum mg_l2addrtype addrtype, struct mg_addr *addr); -// Read an unaligned little-endian value from byte pointer p into a native integer. -// Safe on architectures that forbid unaligned access (e.g. Cortex-M0). -#define MG_LOAD_LE32(p) \ - ((uint32_t) (((uint32_t) MG_U8P(p)[3] << 24U) | \ - ((uint32_t) MG_U8P(p)[2] << 16U) | \ - ((uint32_t) MG_U8P(p)[1] << 8U) | MG_U8P(p)[0])) - bool mg_l2_eth_rx(struct mg_tcpip_if *ifp, enum mg_l2proto *proto, struct mg_str *pay, struct mg_str *raw) { struct eth *eth = (struct eth *) raw->buf; @@ -9814,6 +9807,7 @@ void mg_multicast_restore(struct mg_connection *c, uint8_t *from) { + #if MG_ENABLE_TCPIP #define MG_EPHEMERAL_PORT_BASE 32768 #define PDIFF(a, b) ((size_t) (((char *) (b)) - ((char *) (a)))) @@ -12098,6 +12092,7 @@ void mg_tcpip_qwrite(void *buf, size_t len, struct mg_tcpip_if *ifp) { } void mg_tcpip_init(struct mg_mgr *mgr, struct mg_tcpip_if *ifp) { + mg_usb_init(); // Early, so that the log reaches the USB serial port // If L2 address is not set, make a random one; fill MTU mg_l2_init(ifp); ifp->mtu = ifp->l2mtu; @@ -12264,6 +12259,7 @@ void mg_mgr_poll(struct mg_mgr *mgr, int ms) { mg_timer_poll(&mgr->timers, now); mg_ota_poll(mgr); mg_mdash_poll(mgr); + mg_usb_poll(); // Also without a TCP/IP interface: USB serial only if (mgr->ifp == NULL || mgr->ifp->driver == NULL) return; mg_tcpip_poll(mgr->ifp, now); for (c = mgr->conns; c != NULL; c = tmp) { @@ -37782,6 +37778,974 @@ struct mg_tcpip_driver mg_tcpip_driver_tms570 = {mg_tcpip_driver_tms570_init, #endif +#ifdef MG_ENABLE_LINES +#line 1 "src/drivers/usb.c" +#endif + + + +#if MG_ENABLE_USB + +// Interfaces: NCM control and data 0/1 if enabled, then ACM control and data +#define MG_USB_SERIAL_IF (2 * MG_ENABLE_USB_ETHERNET) +#define MG_USB_NUM_IFS (2 * MG_ENABLE_USB_ETHERNET + 2 * MG_ENABLE_USB_SERIAL) +#define MG_USB_CONFIG_LEN \ + (9 + 85 * MG_ENABLE_USB_ETHERNET + 66 * MG_ENABLE_USB_SERIAL) +#if MG_ENABLE_USB_ETHERNET +#define MG_USB_PRODUCT "MongooseUsbEthernet" +#else +#define MG_USB_PRODUCT "MongooseUsbSerial" +#endif + +// 0xdead is our example VID, for development only +static const uint8_t s_device_desc[] = { + 18, 1, 1, 2, 0xef, 2, 1, 64, 0xde, 0xad, 0xe4, 0x40, 0, 1, 1, 2, 3, 1}; + +// NCM: endpoints 0x81, 0x02/0x82. ACM: endpoints 0x83, 0x04/0x84 +static const uint8_t s_config_desc[] = { + 9, 2, MG_USB_CONFIG_LEN, 0, MG_USB_NUM_IFS, 1, 0, 0x80, 50, // Config +#if MG_ENABLE_USB_ETHERNET + 8, 11, 0, 2, 2, 13, 0, 4, // NCM association + 9, 4, 0, 0, 1, 2, 13, 0, 4, // NCM control interface + 5, 0x24, 0, 0x20, 1, // CDC header + 5, 0x24, 6, 0, 1, // Union + 13, 0x24, 15, 5, 0, 0, 0, 0, 0xea, + 5, 0, 0, 0, // Eth, 1514 bytes + 6, 0x24, 0x1a, 0, 1, 0x21, // NCM 1.0 + 7, 5, 0x81, 3, 16, 0, 16, // Notification endpoint + 9, 4, 1, 0, 0, 10, 0, 1, 0, // Data interface, off + 9, 4, 1, 1, 2, 10, 0, 1, 0, // Data interface, on + 7, 5, 0x02, 2, 64, 0, 0, // Data OUT + 7, 5, 0x82, 2, 64, 0, 0, // Data IN +#endif +#if MG_ENABLE_USB_SERIAL + 8, 11, MG_USB_SERIAL_IF, 2, 2, 2, 1, 6, // ACM association + 9, 4, MG_USB_SERIAL_IF, 0, 1, 2, 2, 1, 6, // ACM control interface + 5, 0x24, 0, 0x20, 1, // CDC header + 5, 0x24, 1, 0, MG_USB_SERIAL_IF + 1, // Call management + 4, 0x24, 2, 2, // ACM + 5, 0x24, 6, MG_USB_SERIAL_IF, MG_USB_SERIAL_IF + 1, // Union + 7, 5, 0x83, 3, 16, 0, 16, // Notification endpoint + 9, 4, MG_USB_SERIAL_IF + 1, 0, 2, 10, 0, 0, 0, // Data interface + 7, 5, 0x04, 2, 64, 0, 0, // Data OUT + 7, 5, 0x84, 2, 64, 0, 0, // Data IN +#endif +}; + +// Endpoint addresses, for CLEAR_FEATURE(ENDPOINT_HALT) +static const uint8_t s_endpoints[] = { +#if MG_ENABLE_USB_ETHERNET + 0x81, 0x02, 0x82, +#endif +#if MG_ENABLE_USB_SERIAL + 0x83, 0x04, 0x84, +#endif +}; + +#if MG_ENABLE_USB_ETHERNET +// Windows 11 binds its NCM driver through a Microsoft OS 2.0 compatible ID +static const uint8_t s_ms_os_desc[] = { + 10, 0, 0, 0, 0, 0, 3, 6, 46, 0, // Set header, Windows 8.1+ + 8, 0, 1, 0, 0, 0, 36, 0, // Configuration subset + 8, 0, 2, 0, 0, 0, 28, 0, // Function subset, NCM + 20, 0, 3, 0, 'W', 'I', 'N', 'N', 'C', 'M', // Compatible ID + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0}; +static const uint8_t s_bos_desc[] = { + 5, 15, 33, 0, 1, 28, 16, 5, 0, 0xdf, + 0x60, 0xdd, 0xd8, 0x89, 0x45, 0xc7, 0x4c, 0x9c, 0xd2, 0x65, + 0x9d, 0x9e, 0x64, 0x8a, 0x9f, 0, 0, 3, 6, sizeof(s_ms_os_desc), + 0, 1, 0}; + +// GET_NTB_PARAMETERS reply: NTB16 only, same limits both ways +static const uint8_t s_ntb_params[] = { + 28, 0, 1, 0, MG_USB_NTB_SIZE & 255, MG_USB_NTB_SIZE >> 8, 0, 0, 4, 0, 0, 0, + 4, 0, 0, 0, MG_USB_NTB_SIZE & 255, MG_USB_NTB_SIZE >> 8, 0, 0, 4, 0, 0, 0, + 4, 0, 16, 0}; + +// Link notifications: speed 12 Mbit/s both ways, connected, disconnected +static const uint8_t s_speed[] = {0xa1, 0x2a, 0, 0, 0, 0, 8, 0, + 0, 0x1b, 0xb7, 0, 0, 0x1b, 0xb7, 0}; +static const uint8_t s_up[] = {0xa1, 0, 1, 0, 0, 0, 0, 0}; +static const uint8_t s_down[] = {0xa1, 0, 0, 0, 0, 0, 0, 0}; + +// Transfer block header for one frame: NTH16, NDP16 with one datagram at +// offset 30, so that the IP header after the 14-byte Ethernet header lands +// on a 4-byte boundary +static const uint8_t s_nth[30] = {'N', 'C', 'M', 'H', 12, 0, 0, 0, 0, 0, + 12, 0, 'N', 'C', 'M', '0', 16, 0, 0, 0, + 30, 0, 0, 0, 0, 0, 0, 0, 0, 0}; +#endif + +// Build string descriptor i in u->buf. Returns its length, 0 if none +static int string_desc(struct mg_usb *u, unsigned i) { + static const char *strings[] = { + NULL, "Mongoose", MG_USB_PRODUCT, NULL, + "USB Ethernet", NULL, "USB Serial"}; + const char *s = i < 7 ? strings[i] : NULL; +#if MG_ENABLE_USB_ETHERNET + char mac[13]; +#endif + size_t k, n; + if (i == 0) return u->buf[0] = 4, u->buf[1] = 3, u->buf[2] = 9, u->buf[3] = 4; + if (i == 3) s = u->serial; +#if MG_ENABLE_USB_ETHERNET + if (i == 5) { // Host end of the link: the device MAC, first byte changed + uint8_t *m = u->ifp->mac; + mg_snprintf(mac, sizeof(mac), "%02X%02X%02X%02X%02X%02X", + ((m[0] ^ 4) | 2) & ~1, m[1], m[2], m[3], m[4], m[5]); + s = mac; + } +#endif + if (s == NULL) return 0; + n = strlen(s) > 32 ? 32 : strlen(s); + memset(u->buf, 0, sizeof(u->buf)); + for (k = 0; k < n; k++) u->buf[2 + k * 2] = (uint8_t) s[k]; + u->buf[0] = (uint8_t) (2 + n * 2), u->buf[1] = 3; + return u->buf[0]; +} + +void mg_usb_reset(struct mg_usb *u) { +#if MG_ENABLE_USB_SERIAL + static const uint8_t line[7] = {0, 0xc2, 1, 0, 0, 0, 8}; // 115200 8N1 + u->dtr = false; + memcpy(u->line, line, sizeof(line)); +#endif +#if MG_ENABLE_USB_ETHERNET + u->alt = false, u->filter = u->sequence = 0, u->notify = 0; + u->input_size = MG_USB_NTB_SIZE; +#endif + u->configured = false; +} + +int mg_usb_setup(struct mg_usb *u, const uint8_t *r, const void **reply) { + unsigned value = MG_LOAD_LE16(r + 2), index = MG_LOAD_LE16(r + 4); + unsigned wlen = MG_LOAD_LE16(r + 6); + const void *d = u->buf; + int n = 0; + switch ((r[0] << 8) | r[1]) { + case 0x8006: // GET_DESCRIPTOR + if (value >> 8 == 1) d = s_device_desc, n = sizeof(s_device_desc); + if (value >> 8 == 2) d = s_config_desc, n = sizeof(s_config_desc); +#if MG_ENABLE_USB_ETHERNET + if (value >> 8 == 15) d = s_bos_desc, n = sizeof(s_bos_desc); +#endif + if (value >> 8 == 3) n = string_desc(u, value & 255); + if (n == 0) return -1; + break; + case 0x0005: // SET_ADDRESS, applied by the driver after the status + if (value > 127) return -1; + break; + case 0x0009: // SET_CONFIGURATION + if (value > 1) return -1; + mg_usb_reset(u); + u->configured = value == 1; + break; + case 0x8008: // GET_CONFIGURATION + u->buf[0] = u->configured, n = 1; + break; + case 0x010b: // SET_INTERFACE: only the Ethernet data interface has 1 + if (index >= MG_USB_NUM_IFS || + value > (unsigned) (MG_ENABLE_USB_ETHERNET && index == 1)) + return -1; +#if MG_ENABLE_USB_ETHERNET + if (index == 1) u->alt = value == 1, u->notify = 1; +#endif + break; + case 0x810a: // GET_INTERFACE + u->buf[0] = 0, n = 1; +#if MG_ENABLE_USB_ETHERNET + if (index == 1) u->buf[0] = u->alt; +#endif + break; +#if MG_ENABLE_USB_ETHERNET + case 0xa183: // GET_NTB_FORMAT: NTB16 +#endif + case 0x8000: // GET_STATUS: device, interface, endpoint + case 0x8100: + case 0x8200: + u->buf[0] = u->buf[1] = 0, n = 2; + break; + case 0x0201: // CLEAR_FEATURE(ENDPOINT_HALT), applied by the driver + if (value || index > 255 || + !memchr(s_endpoints, (int) index, sizeof(s_endpoints))) + return -1; + break; +#if MG_ENABLE_USB_ETHERNET + case 0xc001: // Microsoft OS 2.0 descriptor set + if (index != 7) return -1; + d = s_ms_os_desc, n = sizeof(s_ms_os_desc); + break; + case 0x2143: // SET_ETHERNET_PACKET_FILTER + u->filter = (uint16_t) value; + break; + case 0xa180: // GET_NTB_PARAMETERS + d = s_ntb_params, n = sizeof(s_ntb_params); + break; + case 0x2184: // SET_NTB_FORMAT: NTB16 only + if (value) return -1; + break; + case 0xa185: // GET_NTB_INPUT_SIZE, one datagram per block + memset(u->buf, 0, 8); + MG_STORE_LE32(u->buf, u->input_size); + u->buf[4] = 1, n = 8; + break; + case 0x2186: // SET_NTB_INPUT_SIZE + if ((wlen != 4 && wlen != 8) || MG_LOAD_LE32(r + 8) < 2048 || + MG_LOAD_LE32(r + 8) > 65535) + return -1; + u->input_size = MG_LOAD_LE32(r + 8); + if (u->input_size > MG_USB_NTB_SIZE) u->input_size = MG_USB_NTB_SIZE; + break; +#endif +#if MG_ENABLE_USB_SERIAL + case 0xa121: // GET_LINE_CODING + d = u->line, n = sizeof(u->line); + break; + case 0x2120: // SET_LINE_CODING + if (wlen != sizeof(u->line)) return -1; + memcpy(u->line, r + 8, sizeof(u->line)); + break; + case 0x2122: // SET_CONTROL_LINE_STATE. Closed at 1200 baud: bootloader, + u->dtr = value & 1; // after a delay that lets this request complete + if (!u->dtr && MG_LOAD_LE32(u->line) == 1200) + u->reboot = mg_millis() + 100; + break; + case 0x2123: // SEND_BREAK + break; +#endif + default: + return -1; + } + *reply = d; + return n > (int) wlen ? (int) wlen : n; +} + +#if MG_ENABLE_USB_ETHERNET +size_t mg_usb_notify(struct mg_usb *u, const void **msg) { + if (!u->notify) return 0; + if (u->notify == 1 && u->alt) return u->notify = 2, *msg = s_speed, 16; + u->notify = 0, *msg = u->alt ? s_up : s_down; + return 8; +} + +size_t mg_usb_encode(struct mg_usb *u, uint8_t *p, const void *buf, + size_t len) { + if (!u->alt || !u->filter || len < 14 || len > 1514 || + len + 30 > u->input_size) + return 0; + memcpy(p, s_nth, sizeof(s_nth)); + MG_STORE_LE16(p + 6, u->sequence); + MG_STORE_LE16(p + 8, len + 30); + MG_STORE_LE16(p + 22, len); + memcpy(p + 30, buf, len); + u->sequence++; + return len + 30; +} + +// Offsets come from the host: bound every datagram by the block, and follow +// at most 16 datagram tables so that a cyclic chain cannot loop forever +void mg_usb_decode(struct mg_usb *u, const uint8_t *p, size_t len) { + size_t block, ndp, end, i, ofs, n, tables = 0; + if (len < 12 || MG_LOAD_LE32(p) != 0x484d434e) return; // "NCMH" + block = MG_LOAD_LE16(p + 8), ndp = MG_LOAD_LE16(p + 10); + if (block > len) return; + while (ndp && tables++ < 16 && ndp + 16 <= block && + MG_LOAD_LE32(p + ndp) == 0x304d434e) { // "NCM0" + end = ndp + MG_LOAD_LE16(p + ndp + 4); + for (i = ndp + 8; i + 4 <= end && end <= block; i += 4) { + ofs = MG_LOAD_LE16(p + i), n = MG_LOAD_LE16(p + i + 2); + if (ofs == 0 || n == 0) break; + if (n >= 14 && n <= 1514 && ofs + n <= block) + mg_tcpip_qwrite((void *) (p + ofs), n, u->ifp); + } + ndp = MG_LOAD_LE16(p + ndp + 6); + } +} +#endif + +#if MG_ENABLE_USB_SERIAL +void mg_usb_log(char ch, void *arg) { + struct mg_usb *u = (struct mg_usb *) arg; + if (u->head - u->tail >= MG_USB_LOG_SIZE) u->tail++; + u->log[u->head++ % MG_USB_LOG_SIZE] = ch; +} + +size_t mg_usb_log_read(struct mg_usb *u, void *buf, size_t len) { + size_t n = 0; + while (n < len && u->tail != u->head) { + ((char *) buf)[n++] = u->log[u->tail++ % MG_USB_LOG_SIZE]; + } + return n; +} +#endif + +#endif + +#ifdef MG_ENABLE_LINES +#line 1 "src/drivers/usb_nrf52.c" +#endif + + + + +#if MG_ENABLE_USB && MG_ENABLE_DRIVER_USB_NRF52 +#include + +// nRF52840 USB device controller, polled, full speed. Endpoint buffers are +// inside the controller: EasyDMA moves each packet between them and RAM, +// one transfer at a time, so longer IN transfers go out 64 bytes at a time. +// EasyDMA reads RAM only, thus constant data is copied to RAM first. The +// controller handles SET_ADDRESS by itself. Errata workarounds follow +// Nordic's nrfx_usbd.c: 171, 187 when enabling, 199 around each DMA + +#define ERRATA_199 (*(volatile uint32_t *) 0x40027c1c) + +struct nrf_in { // IN transfer on an endpoint + const uint8_t *data; // Bytes still to send, in RAM + size_t left; // How many + unsigned packets; // Packets still to send + bool busy; // A packet is waiting for the host +}; + +static struct nrf_in s_in[5]; // Index: endpoint number +static struct mg_usb s_usb; +static uint8_t s_req[16]; // SETUP packet, then its OUT data stage +static uint32_t s_ep0[256 / 4]; // Control IN reply, OUT data stage +static char s_serial[17]; // Serial number: device ID in hex +#if MG_ENABLE_USB_ETHERNET +static uint32_t s_note[16 / 4]; // Link notification +static uint32_t s_rx[MG_USB_NTB_SIZE / 4], s_tx[MG_USB_NTB_SIZE / 4]; +static size_t s_rxlen; // Received part of the OUT transfer block +static bool s_discard; // OUT transfer block too long: drop it +#endif +#if MG_ENABLE_USB_SERIAL +static uint32_t s_log[64 / 4]; // Log output in flight +#endif + +// Write an undocumented register the way Nordic's errata workarounds do +static void errata(uint32_t addr, uint32_t value) { + volatile uint32_t *unlock = (volatile uint32_t *) 0x4006ec00; + bool locked = *unlock == 0; + if (locked) *unlock = 0x9375; + *(volatile uint32_t *) addr = value; + if (locked) *unlock = 0x9375; +} + +// Run one EasyDMA transfer and wait for its end event +static void dma(volatile uint32_t *task, volatile uint32_t *end) { + unsigned i; + *end = 0; + ERRATA_199 = 0x82; + *task = 1; + for (i = 0; *end == 0 && i < 100000; i++) (void) 0; // Microseconds + *end = 0; + ERRATA_199 = 0; +} + +// Send the next packet of the IN transfer on ep. False if it is over +static bool in_next(unsigned ep) { + struct nrf_in *e = &s_in[ep]; + size_t n = e->left > 64 ? 64 : e->left; + if (e->packets == 0) return false; + NRF_USBD->EPIN[ep].PTR = (uint32_t) (uintptr_t) e->data; + NRF_USBD->EPIN[ep].MAXCNT = (uint32_t) n; + dma(&NRF_USBD->TASKS_STARTEPIN[ep], &NRF_USBD->EVENTS_ENDEPIN[ep]); + e->data += n, e->left -= n, e->packets--; + return true; +} + +// Start an IN transfer from RAM. zlp: end a multiple of 64 bytes with an +// empty packet +static void in_start(unsigned ep, const void *data, size_t len, bool zlp) { + struct nrf_in *e = &s_in[ep]; + e->data = (const uint8_t *) data, e->left = len; + e->packets = (unsigned) (len / 64 + (len % 64 || len == 0 || zlp)); + e->busy = in_next(ep); +} + +// Data toggle of endpoint address ep back to DATA0 +static void dtoggle(unsigned ep) { + NRF_USBD->DTOGGLE = ep; // Select the endpoint, then set its toggle + NRF_USBD->DTOGGLE = (USBD_DTOGGLE_VALUE_Data0 << USBD_DTOGGLE_VALUE_Pos) | ep; +} + +#if MG_ENABLE_USB_ETHERNET +// Ethernet data endpoints idle, ready to receive +static void data_reset(void) { + dtoggle(0x02), dtoggle(0x82); + memset(&s_in[2], 0, sizeof(s_in[2])); + s_rxlen = 0, s_discard = false; + NRF_USBD->SIZE.EPOUT[2] = 0; // Drop any received packet, accept the next +} + +// A packet on the Ethernet OUT endpoint: add it to the transfer block. The +// endpoint accepts the next packet once this one is moved or dropped +static void rx(void) { + size_t n = NRF_USBD->SIZE.EPOUT[2]; + if (n > 0 && !s_discard && s_rxlen + n <= sizeof(s_rx)) { + uint8_t *p = (uint8_t *) s_rx + s_rxlen; + NRF_USBD->EPOUT[2].PTR = (uint32_t) (uintptr_t) p; + NRF_USBD->EPOUT[2].MAXCNT = (uint32_t) n; + dma(&NRF_USBD->TASKS_STARTEPOUT[2], &NRF_USBD->EVENTS_ENDEPOUT[2]); + s_rxlen += n; + } else { + s_discard = s_discard || n > 0; // An empty packet only ends the block + NRF_USBD->SIZE.EPOUT[2] = 0; + } + // At the advertised maximum OUT size, the host need not send a ZLP. + // Other transfers end with a short packet (including a ZLP) + if (n < 64 || s_rxlen == sizeof(s_rx)) { + if (!s_discard) mg_usb_decode(&s_usb, (uint8_t *) s_rx, s_rxlen); + s_rxlen = 0, s_discard = false; + } +} +#endif + +// Endpoints 1-4 on and idle if configured, else off +static void endpoints_reset(void) { + memset(s_in, 0, sizeof(s_in)); + NRF_USBD->EPINEN = 1, NRF_USBD->EPOUTEN = 1; + if (!s_usb.configured) return; +#if MG_ENABLE_USB_ETHERNET + NRF_USBD->EPINEN |= MG_BIT(1) | MG_BIT(2), NRF_USBD->EPOUTEN |= MG_BIT(2); + dtoggle(0x81); + data_reset(); +#endif +#if MG_ENABLE_USB_SERIAL + NRF_USBD->EPINEN |= MG_BIT(3) | MG_BIT(4), NRF_USBD->EPOUTEN |= MG_BIT(4); + dtoggle(0x83), dtoggle(0x04), dtoggle(0x84); + NRF_USBD->SIZE.EPOUT[4] = 0; +#endif +} + +// Run a complete control request: SETUP in s_req, then any OUT data +static void request(void) { + const void *reply; + unsigned wlen = MG_LOAD_LE16(s_req + 6); + int n = mg_usb_setup(&s_usb, s_req, &reply); + if (n < 0) { + NRF_USBD->TASKS_EP0STALL = 1; + return; + } + switch ((s_req[0] << 8) | s_req[1]) { + case 0x0009: // SET_CONFIGURATION + endpoints_reset(); + break; +#if MG_ENABLE_USB_ETHERNET + case 0x010b: // SET_INTERFACE + if (s_req[4] == 1) data_reset(); + break; +#endif + case 0x0201: // CLEAR_FEATURE(ENDPOINT_HALT) + dtoggle(s_req[4]); + NRF_USBD->EPSTALL = + (USBD_EPSTALL_STALL_UnStall << USBD_EPSTALL_STALL_Pos) | s_req[4]; + if (!(s_req[4] & 0x80)) NRF_USBD->SIZE.EPOUT[s_req[4] & 15] = 0; + break; + } + if ((s_req[0] & 0x80) && wlen) { // IN data stage. Largest reply: 160 + memcpy(s_ep0, reply, (size_t) n); + in_start(0, s_ep0, (size_t) n, n < (int) wlen); + } else { + NRF_USBD->TASKS_EP0STATUS = 1; + } +} + +// A SETUP packet: run it, or first receive its OUT data stage +static void setup(void) { + const volatile uint32_t *regs = &NRF_USBD->BMREQUESTTYPE; + unsigned i, wlen; + for (i = 0; i < 8; i++) s_req[i] = (uint8_t) regs[i]; + wlen = MG_LOAD_LE16(s_req + 6); + memset(&s_in[0], 0, sizeof(s_in[0])); // Cancels the previous transfer + if (s_req[0] == 0 && s_req[1] == 5) return; // SET_ADDRESS: hardware's + if ((s_req[0] & 0x80) || wlen == 0) { + request(); + } else if (wlen > sizeof(s_req) - 8) { + NRF_USBD->TASKS_EP0STALL = 1; + } else { + NRF_USBD->TASKS_EP0RCVOUT = 1; // Accept the OUT data stage + } +} + +// A control data stage packet: an IN one acknowledged, or an OUT one arrived +static void ep0_data(void) { + size_t n = NRF_USBD->SIZE.EPOUT[0]; + if (s_req[0] & 0x80) { + if (!in_next(0)) NRF_USBD->TASKS_EP0STATUS = 1; + } else if (n != MG_LOAD_LE16(s_req + 6)) { + NRF_USBD->TASKS_EP0STALL = 1; + } else { + NRF_USBD->EPOUT[0].PTR = (uint32_t) (uintptr_t) s_ep0; + NRF_USBD->EPOUT[0].MAXCNT = (uint32_t) n; + dma(&NRF_USBD->TASKS_STARTEPOUT[0], &NRF_USBD->EVENTS_ENDEPOUT[0]); + memcpy(s_req + 8, s_ep0, n); + request(); + } +} + +// Follow USB power: enable the controller when VBUS appears, attach to the +// bus once both are ready, and detach when VBUS goes. True while attached +static bool attach(void) { + uint32_t power = NRF_POWER->USBREGSTATUS; + if (!(power & POWER_USBREGSTATUS_VBUSDETECT_Msk)) { + if (NRF_USBD->ENABLE) { + NRF_USBD->USBPULLUP = 0, NRF_USBD->ENABLE = 0; + mg_usb_reset(&s_usb); + } + return false; + } + if (!NRF_USBD->ENABLE) { + errata(0x4006ed14, 3); // Errata 187 + errata(0x4006ec14, 0xc0); // Errata 171 + NRF_USBD->EVENTCAUSE = USBD_EVENTCAUSE_READY_Msk; + NRF_USBD->ENABLE = 1; + } + if (NRF_USBD->USBPULLUP) return true; + if (!(NRF_USBD->EVENTCAUSE & USBD_EVENTCAUSE_READY_Msk) || + !(power & POWER_USBREGSTATUS_OUTPUTRDY_Msk)) + return false; + NRF_USBD->EVENTCAUSE = USBD_EVENTCAUSE_READY_Msk; + errata(0x4006ec14, 0); + errata(0x4006ed14, 0); + NRF_USBD->USBPULLUP = 1; + return true; +} + +void mg_usb_init(void) { + static bool started; + uint32_t id[2], xtal = CLOCK_HFCLKSTAT_SRC_Msk | CLOCK_HFCLKSTAT_STATE_Msk; + if (started) return; + started = true; + id[0] = NRF_FICR->DEVICEID[0], id[1] = NRF_FICR->DEVICEID[1]; + mg_snprintf(s_serial, sizeof(s_serial), "%M", mg_print_hex, (int) sizeof(id), + (uint8_t *) id); + s_usb.serial = s_serial; + mg_usb_reset(&s_usb); +#if MG_ENABLE_USB_SERIAL + mg_log_set_fn(mg_usb_log, &s_usb); // Log to the USB serial port +#endif + if ((NRF_CLOCK->HFCLKSTAT & xtal) != xtal) { // USB needs the crystal + NRF_CLOCK->TASKS_HFCLKSTART = 1; + while ((NRF_CLOCK->HFCLKSTAT & xtal) != xtal) (void) 0; + } + // The controller itself starts in mg_usb_poll(), once USB power is there +} + +void mg_usb_poll(void) { + mg_usb_init(); +#if MG_ENABLE_USB_SERIAL + if (s_usb.reboot && mg_millis() > s_usb.reboot) { + NRF_POWER->GPREGRET = 0x57; // Adafruit bootloader: stay in DFU mode + NVIC_SystemReset(); + } +#endif + if (!attach()) return; + if (NRF_USBD->EVENTS_USBRESET) { + NRF_USBD->EVENTS_USBRESET = 0; + NRF_USBD->EVENTS_EP0DATADONE = NRF_USBD->EVENTS_EPDATA = 0; + NRF_USBD->EPDATASTATUS = NRF_USBD->EPDATASTATUS; + mg_usb_reset(&s_usb); + endpoints_reset(); + return; + } + if (NRF_USBD->EVENTS_EP0DATADONE) { // Before a new SETUP replaces s_req + NRF_USBD->EVENTS_EP0DATADONE = 0; + ep0_data(); + } + if (NRF_USBD->EVENTS_EP0SETUP) { + NRF_USBD->EVENTS_EP0SETUP = 0; + setup(); + } + if (NRF_USBD->EVENTS_EPDATA) { // Bit n: IN n acknowledged, 16+n: OUT n + uint32_t done = NRF_USBD->EPDATASTATUS; + unsigned i; + NRF_USBD->EVENTS_EPDATA = 0; + NRF_USBD->EPDATASTATUS = done; + for (i = 1; i < 5; i++) { + if (done & MG_BIT(i)) s_in[i].busy = in_next(i); + } +#if MG_ENABLE_USB_ETHERNET + if (done & MG_BIT(18)) rx(); +#endif +#if MG_ENABLE_USB_SERIAL + if (done & MG_BIT(20)) NRF_USBD->SIZE.EPOUT[4] = 0; // Serial: ignored +#endif + } +#if MG_ENABLE_USB_ETHERNET + { + const void *msg; + size_t n; + if (!s_in[1].busy && (n = mg_usb_notify(&s_usb, &msg)) > 0) { + memcpy(s_note, msg, n); + in_start(1, s_note, n, false); + } + } +#endif +#if MG_ENABLE_USB_SERIAL + if (s_usb.configured && s_usb.dtr && !s_in[4].busy) { + size_t n = mg_usb_log_read(&s_usb, s_log, sizeof(s_log)); + if (n > 0) in_start(4, s_log, n, true); + } +#endif +} + +#if MG_ENABLE_USB_ETHERNET +static bool mg_tcpip_driver_usb_nrf52_init(struct mg_tcpip_if *ifp) { + s_usb.ifp = ifp; // mg_tcpip_init() has started USB already + return true; +} + +static size_t mg_tcpip_driver_usb_nrf52_tx(const void *buf, size_t len, + struct mg_tcpip_if *ifp) { + // One frame can be in flight. Keep USB moving while waiting, but bound + // the wait if the host stops reading or the cable is gone + uint64_t until = mg_millis() + 20; + size_t n = 0; + while (s_in[2].busy && mg_millis() < until) mg_usb_poll(); + if (!s_in[2].busy) n = mg_usb_encode(&s_usb, (uint8_t *) s_tx, buf, len); + if (n) in_start(2, s_tx, n, n < s_usb.input_size); + (void) ifp; + return n ? len : 0; +} + +// USB itself runs from mg_mgr_poll(). Report the link: Ethernet open +static bool mg_tcpip_driver_usb_nrf52_poll(struct mg_tcpip_if *ifp, bool s1) { + (void) ifp; + return s1 && s_usb.alt && s_usb.filter; +} + +struct mg_tcpip_driver mg_tcpip_driver_usb_nrf52 = { + mg_tcpip_driver_usb_nrf52_init, mg_tcpip_driver_usb_nrf52_tx, NULL, + mg_tcpip_driver_usb_nrf52_poll}; +#endif + +#endif + +#ifdef MG_ENABLE_LINES +#line 1 "src/drivers/usb_rp.c" +#endif + + + + +#if MG_ENABLE_USB && MG_ENABLE_DRIVER_USB_RP + +// RP2040 / RP2350 USB device controller: single core, polled, full speed, +// 64-byte single-buffered endpoints in USB DPRAM. Longer IN transfers go +// out one packet at a time, the next one when the previous completes + +struct rp_ep { + uint8_t *buf; // Endpoint buffer in USB DPRAM + io_rw_32 *ctrl; // Buffer control register + const uint8_t *data; // IN transfer: bytes still to send + size_t left; // IN transfer: how many + unsigned packets; // IN transfer: packets still to send + uint8_t pid; // Next DATA PID, 0 or 1 + bool busy; // Buffer handed to the controller +}; + +static struct rp_ep s_ep[5][2]; // Index: endpoint number, OUT=0 IN=1 +static struct mg_usb s_usb; +static uint8_t s_req[16]; // SETUP packet, then its OUT data stage +static bool s_req_out; // Waiting for that OUT data stage +static uint8_t s_address; // Address to apply after the status stage +static char s_serial[2 * PICO_UNIQUE_BOARD_ID_SIZE_BYTES + 1]; +#if MG_ENABLE_USB_ETHERNET +static uint8_t s_rx[MG_USB_NTB_SIZE], s_tx[MG_USB_NTB_SIZE]; +static size_t s_rxlen; // Received part of the OUT transfer block +static bool s_discard; // OUT transfer block too long: drop it +#endif +#if MG_ENABLE_USB_SERIAL +static char s_log[64]; // Log output in flight +#endif + +// Hand one packet buffer to the controller. OUT: accept up to len bytes +static void packet(unsigned ep, bool in, const void *data, unsigned len) { + struct rp_ep *e = &s_ep[ep][in]; + uint32_t v = len | (e->pid ? USB_BUF_CTRL_DATA1_PID : 0) | + (in ? USB_BUF_CTRL_FULL : 0); + if (in && len) memcpy(e->buf, data, len); + e->pid ^= 1; + e->busy = true; + *e->ctrl = v; + // RP2040 datasheet: allow at least 12 cycles between writing buffer + // metadata and handing ownership to the controller through AVAIL + busy_wait_at_least_cycles(12); + *e->ctrl = v | USB_BUF_CTRL_AVAIL; +} + +// Send the next packet of the IN transfer on ep. False if it is over +static bool in_next(unsigned ep) { + struct rp_ep *e = &s_ep[ep][1]; + unsigned n = e->left > 64 ? 64 : (unsigned) e->left; + if (e->packets == 0) return false; + packet(ep, true, e->data, n); + e->data += n, e->left -= n, e->packets--; + return true; +} + +// Start an IN transfer. zlp: end a multiple of 64 bytes with an empty packet +static void in_start(unsigned ep, const void *data, size_t len, bool zlp) { + struct rp_ep *e = &s_ep[ep][1]; + e->data = (const uint8_t *) data, e->left = len; + e->packets = (unsigned) (len / 64 + (len % 64 || len == 0 || zlp)); + in_next(ep); +} + +// Set up endpoint ep, direction in, idle. Endpoints 1 and 3 are interrupt, +// 2 and 4 bulk, each with a 64-byte DPRAM buffer of its own +static void ep_init(unsigned ep, bool in) { + struct rp_ep *e = &s_ep[ep][in]; + e->ctrl = in ? &usb_dpram->ep_buf_ctrl[ep].in + : &usb_dpram->ep_buf_ctrl[ep].out; + e->buf = ep ? &usb_dpram->epx_data[(ep * 2 + in) * 64] : usb_dpram->ep0_buf_a; + e->pid = 0, e->busy = false, e->packets = 0; + *e->ctrl = 0; + if (ep) { + io_rw_32 *ctrl = in ? &usb_dpram->ep_ctrl[ep - 1].in + : &usb_dpram->ep_ctrl[ep - 1].out; + *ctrl = EP_CTRL_ENABLE_BITS | EP_CTRL_INTERRUPT_PER_BUFFER | + ((ep & 1 ? 3U : 2U) << EP_CTRL_BUFFER_TYPE_LSB) | + (uint32_t) ((uintptr_t) e->buf - (uintptr_t) usb_dpram); + } +} + +#if MG_ENABLE_USB_ETHERNET +// Ethernet data endpoints idle, then armed to receive if Ethernet is open +static void data_reset(void) { + ep_init(2, false), ep_init(2, true); + s_rxlen = 0, s_discard = false; + if (s_usb.alt) packet(2, false, NULL, 64); +} + +// A packet on the Ethernet OUT endpoint: add it to the transfer block +static void rx(const uint8_t *buf, unsigned n) { + if (s_rxlen + n <= sizeof(s_rx) && !s_discard) { + memcpy(s_rx + s_rxlen, buf, n); + s_rxlen += n; + } else { + s_discard = true; + } + // At the advertised maximum OUT size, the host need not send a ZLP. + // Other transfers end with a short packet (including a ZLP) + if (n < 64 || s_rxlen == sizeof(s_rx)) { + if (!s_discard) mg_usb_decode(&s_usb, s_rx, s_rxlen); + s_rxlen = 0; + s_discard = false; + } + if (s_usb.alt) packet(2, false, NULL, 64); +} +#endif + +// All endpoints idle, then the serial port armed to receive if configured +static void endpoints_reset(void) { + static const uint8_t eps[] = { + 0x00, 0x80, +#if MG_ENABLE_USB_ETHERNET + 0x81, +#endif +#if MG_ENABLE_USB_SERIAL + 0x83, 0x04, 0x84, +#endif + }; + size_t i; + for (i = 0; i < sizeof(eps); i++) ep_init(eps[i] & 15U, eps[i] >> 7); +#if MG_ENABLE_USB_ETHERNET + data_reset(); +#endif +#if MG_ENABLE_USB_SERIAL + if (s_usb.configured) packet(4, false, NULL, 64); +#endif +} + +// Stall endpoint 0 until the next SETUP +static void stall(void) { + usb_hw->ep_stall_arm = + USB_EP_STALL_ARM_EP0_IN_BITS | USB_EP_STALL_ARM_EP0_OUT_BITS; + *s_ep[0][1].ctrl = USB_BUF_CTRL_STALL; + *s_ep[0][0].ctrl = USB_BUF_CTRL_STALL; +} + +// Run a complete control request: SETUP in s_req, then any OUT data +static void request(void) { + const void *reply; + int n = mg_usb_setup(&s_usb, s_req, &reply); + if (n < 0) { + stall(); + return; + } + switch ((s_req[0] << 8) | s_req[1]) { + case 0x0005: // SET_ADDRESS, applied after the status stage + s_address = s_req[2]; + break; + case 0x0009: // SET_CONFIGURATION + endpoints_reset(); + break; +#if MG_ENABLE_USB_ETHERNET + case 0x010b: // SET_INTERFACE + if (s_req[4] == 1) data_reset(); + break; +#endif + case 0x0201: { // CLEAR_FEATURE(ENDPOINT_HALT) + struct rp_ep *e = &s_ep[s_req[4] & 15][s_req[4] >> 7]; + *e->ctrl &= ~USB_BUF_CTRL_STALL, e->pid = 0; + break; + } + } + // IN data stage, or the status stage, both starting with DATA1 + s_ep[0][1].pid = 1; + in_start(0, reply, (size_t) n, n < (int) MG_LOAD_LE16(s_req + 6)); +} + +// A SETUP packet: run it, or first receive its OUT data stage +static void setup(void) { + unsigned wlen; + memcpy(s_req, (const void *) usb_dpram->setup_packet, 8); + wlen = MG_LOAD_LE16(s_req + 6); + // A SETUP cancels the preceding control transfer. OUT stages use DATA1 + ep_init(0, false), ep_init(0, true); + s_ep[0][0].pid = 1; + s_address = 0, s_req_out = false; + if ((s_req[0] & 0x80) || wlen == 0) { + request(); + } else if (wlen > sizeof(s_req) - 8) { + stall(); + } else { + s_req_out = true; + packet(0, false, NULL, 64); + } +} + +// A buffer the controller has finished with +static void complete(unsigned ep, bool in) { + struct rp_ep *e = &s_ep[ep][in]; + unsigned n = *e->ctrl & USB_BUF_CTRL_LEN_MASK; + e->busy = false; + if (in && in_next(ep)) return; + if (ep == 0 && in) { // Control IN data or status stage sent + if (s_address) { + usb_hw->dev_addr_ctrl = s_address, s_address = 0; + } else if ((s_req[0] & 0x80) && MG_LOAD_LE16(s_req + 6)) { + packet(0, false, NULL, 64); // Host's OUT status stage + } + } else if (ep == 0 && !in && s_req_out) { // Control OUT data stage + s_req_out = false; + if (n != MG_LOAD_LE16(s_req + 6)) { + stall(); + } else { + memcpy(s_req + 8, e->buf, n); + request(); + } +#if MG_ENABLE_USB_ETHERNET + } else if (ep == 2 && !in) { + rx(e->buf, n); +#endif +#if MG_ENABLE_USB_SERIAL + } else if (ep == 4 && !in) { + packet(4, false, NULL, 64); // Serial input is discarded: log console +#endif + } +} + +void mg_usb_init(void) { + static bool started; + if (started) return; + started = true; + pico_get_unique_board_id_string(s_serial, sizeof(s_serial)); + s_usb.serial = s_serial; + mg_usb_reset(&s_usb); +#if MG_ENABLE_USB_SERIAL + mg_log_set_fn(mg_usb_log, &s_usb); // Log to the USB serial port +#endif + reset_block(RESETS_RESET_USBCTRL_BITS); + unreset_block_wait(RESETS_RESET_USBCTRL_BITS); + memset(usb_dpram, 0, sizeof(*usb_dpram)); + usb_hw->muxing = USB_USB_MUXING_TO_PHY_BITS | USB_USB_MUXING_SOFTCON_BITS; + usb_hw->pwr = + USB_USB_PWR_VBUS_DETECT_BITS | USB_USB_PWR_VBUS_DETECT_OVERRIDE_EN_BITS; + usb_hw->main_ctrl = USB_MAIN_CTRL_CONTROLLER_EN_BITS; + usb_hw->sie_ctrl = USB_SIE_CTRL_EP0_INT_1BUF_BITS; + usb_hw->inte = 0; // Poll raw status instead of an interrupt handler + endpoints_reset(); + hw_set_bits(&usb_hw->sie_ctrl, USB_SIE_CTRL_PULLUP_EN_BITS); +} + +void mg_usb_poll(void) { + uint32_t status, done; + unsigned i; + mg_usb_init(); + status = usb_hw->intr; +#if MG_ENABLE_USB_SERIAL + if (s_usb.reboot && mg_millis() > s_usb.reboot) reset_usb_boot(0, 0); +#endif + if (status & USB_INTR_BUS_RESET_BITS) { + usb_hw->sie_status = USB_SIE_STATUS_BUS_RESET_BITS; + usb_hw->dev_addr_ctrl = 0; + usb_hw->buf_status = 0xffffffff; + mg_usb_reset(&s_usb); + endpoints_reset(); + return; + } + if (status & USB_INTR_SETUP_REQ_BITS) { + // Discard stale EP0 completions from an interrupted control transfer + usb_hw->buf_status = 3; + usb_hw->sie_status = USB_SIE_STATUS_SETUP_REC_BITS; + setup(); + } + done = usb_hw->buf_status; + for (i = 0; i < 10; i++) { // Bits: EP0 IN, EP0 OUT, EP1 IN, ... + if (!(done & (1U << i))) continue; + usb_hw->buf_status = 1U << i; + if (s_ep[i / 2][!(i & 1)].ctrl) complete(i / 2, !(i & 1)); + } +#if MG_ENABLE_USB_ETHERNET + if (!s_ep[1][1].busy) { + const void *msg; + size_t n = mg_usb_notify(&s_usb, &msg); + if (n) in_start(1, msg, n, false); + } +#endif +#if MG_ENABLE_USB_SERIAL + if (s_usb.configured && s_usb.dtr && !s_ep[4][1].busy) { + size_t n = mg_usb_log_read(&s_usb, s_log, sizeof(s_log)); + if (n) in_start(4, s_log, n, true); + } +#endif +} + +#if MG_ENABLE_USB_ETHERNET +static bool mg_tcpip_driver_usb_rp_init(struct mg_tcpip_if *ifp) { + s_usb.ifp = ifp; // mg_tcpip_init() has started USB already + return true; +} + +static size_t mg_tcpip_driver_usb_rp_tx(const void *buf, size_t len, + struct mg_tcpip_if *ifp) { + // One frame can be in flight. Keep USB moving while waiting, but bound + // the wait if the host stops reading or the cable is gone + uint64_t until = mg_millis() + 20; + size_t n = 0; + while (s_ep[2][1].busy && mg_millis() < until) mg_usb_poll(); + if (!s_ep[2][1].busy) n = mg_usb_encode(&s_usb, s_tx, buf, len); + if (n) in_start(2, s_tx, n, n < s_usb.input_size); + (void) ifp; + return n ? len : 0; +} + +// USB itself runs from mg_mgr_poll(). Report the link: Ethernet open +static bool mg_tcpip_driver_usb_rp_poll(struct mg_tcpip_if *ifp, bool s1) { + (void) ifp; + return s1 && s_usb.alt && s_usb.filter; +} + +struct mg_tcpip_driver mg_tcpip_driver_usb_rp = { + mg_tcpip_driver_usb_rp_init, mg_tcpip_driver_usb_rp_tx, NULL, + mg_tcpip_driver_usb_rp_poll}; +#endif + +#endif + #ifdef MG_ENABLE_LINES #line 1 "src/drivers/w5100.c" #endif diff --git a/mongoose.h b/mongoose.h index adc5ad52..450e24f5 100644 --- a/mongoose.h +++ b/mongoose.h @@ -519,22 +519,23 @@ extern "C" { #include #include -#include +#include #include +#include #include int mkdir(const char *, mode_t); #if MG_OTA == MG_OTA_PICOSDK #include -#include #include +#include #include #ifndef MG_OTA_WATCHDOG_MS #if PICO_RP2040 -#define MG_OTA_WATCHDOG_MS 8000U // max delay on RP2040 is 8.3 seconds +#define MG_OTA_WATCHDOG_MS 8000U // max delay on RP2040 is 8.3 seconds #else -#define MG_OTA_WATCHDOG_MS 10000U // max delay on RP2350 is 16 seconds +#define MG_OTA_WATCHDOG_MS 10000U // max delay on RP2350 is 16 seconds #endif #endif @@ -551,17 +552,17 @@ int mkdir(const char *, mode_t); (watchdog_hw->scratch[0] = (uint32_t) (v), (uint32_t) watchdog_hw->scratch[0]) #if PICO_RP2040 -#define MG_OTA_ROLLBACK() \ - do { \ - mg_flash->swap_fn(); \ - *(volatile unsigned long *) 0xe000ed0c = 0x5fa0004; \ +#define MG_OTA_ROLLBACK() \ + do { \ + mg_flash->swap_fn(); \ + *(volatile unsigned long *) 0xe000ed0c = 0x5fa0004; \ } while (0) #else -#define MG_OTA_ROLLBACK() \ - do { \ - mg_flash->swap_fn(); \ - ((rom_reboot_fn) rom_func_lookup(ROM_FUNC_REBOOT))( \ - BOOT_TYPE_NORMAL | 0x100, 1, 0, 0); \ +#define MG_OTA_ROLLBACK() \ + do { \ + mg_flash->swap_fn(); \ + ((rom_reboot_fn) rom_func_lookup(ROM_FUNC_REBOOT))( \ + BOOT_TYPE_NORMAL | 0x100, 1, 0, 0); \ } while (0) #endif #endif @@ -1319,6 +1320,26 @@ struct timeval { #define MG_ENABLE_TCPIP_TCPRTX 0 // TCP retransmission queue #endif +#ifndef MG_ENABLE_DRIVER_USB_RP +#define MG_ENABLE_DRIVER_USB_RP 0 // USB device, RP2040 / RP2350 +#endif + +#ifndef MG_ENABLE_DRIVER_USB_SAMD21 +#define MG_ENABLE_DRIVER_USB_SAMD21 0 // USB device, SAMD21 +#endif + +#ifndef MG_ENABLE_DRIVER_USB_NRF52 +#define MG_ENABLE_DRIVER_USB_NRF52 0 // USB device, nRF52840 +#endif + +#ifndef MG_ENABLE_USB_ETHERNET +#define MG_ENABLE_USB_ETHERNET 0 // USB driver: CDC-NCM Ethernet interface +#endif + +#ifndef MG_ENABLE_USB_SERIAL +#define MG_ENABLE_USB_SERIAL 0 // USB driver: CDC-ACM serial log console +#endif + #ifndef MG_TCPIP_DHCPNAME_SIZE #define MG_TCPIP_DHCPNAME_SIZE 18 // struct mg_tcpip_if :: dhcp_name size #endif @@ -2044,6 +2065,26 @@ uint64_t mg_timegm(unsigned int year, unsigned int month, unsigned int day, MG_U8P(p)[7] = (uint8_t) (n); \ } while (0) +// Little-endian counterparts, e.g. for USB. Safe for unaligned access +#define MG_LOAD_LE16(p) \ + ((uint16_t) (((uint16_t) MG_U8P(p)[1] << 8U) | MG_U8P(p)[0])) +#define MG_LOAD_LE32(p) \ + ((uint32_t) (((uint32_t) MG_U8P(p)[3] << 24U) | \ + ((uint32_t) MG_U8P(p)[2] << 16U) | \ + ((uint32_t) MG_U8P(p)[1] << 8U) | MG_U8P(p)[0])) +#define MG_STORE_LE16(p, n) \ + do { \ + MG_U8P(p)[0] = (uint8_t) (n); \ + MG_U8P(p)[1] = (uint8_t) ((n) >> 8U); \ + } while (0) +#define MG_STORE_LE32(p, n) \ + do { \ + MG_U8P(p)[0] = (uint8_t) (n); \ + MG_U8P(p)[1] = (uint8_t) ((n) >> 8U); \ + MG_U8P(p)[2] = (uint8_t) ((n) >> 16U); \ + MG_U8P(p)[3] = (uint8_t) ((n) >> 24U); \ + } while (0) + // Network / host byte-order conversion (big-endian <-> native). // mg_htons/mg_htonl/mg_htonll are aliases for the same operation (symmetric). uint16_t mg_ntohs(uint16_t net); @@ -6249,6 +6290,164 @@ extern struct mg_tcpip_driver mg_tcpip_driver_tms570; +// USB device, independent of the controller: CDC-NCM Ethernet, enabled by +// MG_ENABLE_USB_ETHERNET, and a CDC-ACM serial port that carries the +// Mongoose log, enabled by MG_ENABLE_USB_SERIAL. The controller drivers +// are usb_rp.c, usb_samd21.c and usb_nrf52.c, enabled by +// MG_ENABLE_DRIVER_USB_*. Mongoose runs USB from mg_tcpip_init() and +// mg_mgr_poll(), so user code needs no USB calls + +#if MG_ENABLE_TCPIP && \ + (MG_ENABLE_DRIVER_USB_RP || MG_ENABLE_DRIVER_USB_SAMD21 || \ + MG_ENABLE_DRIVER_USB_NRF52) && \ + (MG_ENABLE_USB_ETHERNET || MG_ENABLE_USB_SERIAL) +#define MG_ENABLE_USB 1 + +// #if defined(MG_ENABLE_DRIVER_USB_SAMD21) && MG_ENABLE_DRIVER_USB_SAMD21 +// #define MG_USB_DEFAULT_SIZE 2048 // SAMD21: 32k RAM +// #else +// #define MG_USB_DEFAULT_SIZE 4096 +// #endif +#define MG_USB_DEFAULT_SIZE 2048 +#ifndef MG_USB_NTB_SIZE // Transfer block buffer, each direction, >= 2048 +#define MG_USB_NTB_SIZE MG_USB_DEFAULT_SIZE +#endif +#ifndef MG_USB_LOG_SIZE // Serial log ring buffer +#define MG_USB_LOG_SIZE (MG_USB_DEFAULT_SIZE / 2) +#endif +#ifndef MG_USB_QUEUE_SIZE // TCP/IP stack receive queue +#define MG_USB_QUEUE_SIZE (MG_USB_DEFAULT_SIZE * 2) +#endif + +// Endpoints: 1 interrupt IN, link notifications. 2 bulk IN/OUT, Ethernet. +// 3 interrupt IN, serial notifications (unused). 4 bulk IN/OUT, serial + +struct mg_usb { + const char *serial; // USB serial number, set by the driver + bool configured; // Host has set the configuration + uint8_t buf[66]; // Generated replies +#if MG_ENABLE_USB_ETHERNET + struct mg_tcpip_if *ifp; // TCP/IP interface, set by the driver + bool alt; // Ethernet open: data interface setting 1 + uint16_t filter, sequence; // Host packet filter, next IN block number + uint32_t input_size; // Largest IN block the host accepts + uint8_t notify; // Pending link notifications +#endif +#if MG_ENABLE_USB_SERIAL + bool dtr; // Terminal open + uint64_t reboot; // mg_millis() to enter the bootloader, or 0 + uint8_t line[7]; // Serial line coding + char log[MG_USB_LOG_SIZE]; // Serial log ring buffer + unsigned head, tail; // Log ring write and read counters +#endif +}; + +// Implemented by the enabled controller driver. Start the controller, once, +// and send the log to the serial port +void mg_usb_init(void); + +// Implemented by the enabled controller driver. Run the controller. Calls +// mg_usb_init() first, so it works without a TCP/IP interface too +void mg_usb_poll(void); + +// Unconfigured state, on start and after a bus reset. Keeps the log +void mg_usb_reset(struct mg_usb *u); + +// Handle an 8-byte SETUP packet, followed by its OUT data stage if it has +// one. Returns -1 to stall, else the IN reply length, 0 for status only +int mg_usb_setup(struct mg_usb *u, const uint8_t *req, const void **reply); + +#if MG_ENABLE_USB_ETHERNET +// Next link notification for endpoint 1. Returns its length, 0 if none +size_t mg_usb_notify(struct mg_usb *u, const void **msg); + +// Wrap an Ethernet frame into a transfer block at ntb. Returns the block +// length, 0 if the link is down or the frame does not fit +size_t mg_usb_encode(struct mg_usb *u, uint8_t *ntb, const void *buf, + size_t len); + +// Queue the Ethernet frames of a received transfer block to the TCP/IP stack +void mg_usb_decode(struct mg_usb *u, const uint8_t *ntb, size_t len); +#endif + +#if MG_ENABLE_USB_SERIAL +// Log output function for mg_log_set_fn(mg_usb_log, u). Keeps the latest +// MG_USB_LOG_SIZE characters +void mg_usb_log(char ch, void *u); + +// Take up to len logged characters into buf. Returns how many +size_t mg_usb_log_read(struct mg_usb *u, void *buf, size_t len); +#endif + +#else +#define MG_ENABLE_USB 0 +#define mg_usb_init() +#define mg_usb_poll() +#endif + + +// nRF52840 USB device controller, see usb.h: CDC-NCM Ethernet and a CDC-ACM +// serial log console. No TinyUSB, polled. Needs the nRF52840 device headers +// from nrfx/mdk on the include path. Example: tutorials/nordic/xiao-52840 + +#if MG_ENABLE_USB && MG_ENABLE_DRIVER_USB_NRF52 && MG_ENABLE_USB_ETHERNET + +extern struct mg_tcpip_driver mg_tcpip_driver_usb_nrf52; + +// Set MG_TCPIP_IP to give the device a static address and serve DHCP to the +// USB host. Leave it unset to get an address over DHCP, e.g. from macOS +// Internet Sharing. The device MAC comes from MG_SET_MAC_ADDRESS, random if +// it is not set; the host end of the link gets a MAC derived from it +#define MG_TCPIP_DRIVER_USB_NRF52_INIT(mgr) \ + do { \ + static struct mg_tcpip_if mif_; \ + mif_.ip = MG_TCPIP_IP; \ + mif_.mask = MG_TCPIP_MASK; \ + mif_.gw = MG_TCPIP_GW; \ + mif_.enable_dhcp_server = mif_.ip != 0; \ + mif_.driver = &mg_tcpip_driver_usb_nrf52; \ + mif_.recv_queue.size = MG_USB_QUEUE_SIZE; \ + MG_SET_MAC_ADDRESS(mif_.mac); \ + mg_tcpip_init(mgr, &mif_); \ + MG_INFO(("Driver: usb_nrf52, MAC: %M", mg_print_mac, mif_.mac)); \ + } while (0) + +// Like nrf52.h: both nRF52 drivers can be enabled at once, e.g. in a bridge +#ifndef MG_TCPIP_DRIVER_INIT +#define MG_TCPIP_DRIVER_INIT(mgr) MG_TCPIP_DRIVER_USB_NRF52_INIT(mgr) +#endif + +#endif + + +// RP2040 / RP2350 native USB controller, see usb.h: CDC-NCM Ethernet and +// a CDC-ACM serial log console. No TinyUSB, polled. Example: tutorials/rp/usb + +#if MG_ENABLE_USB && MG_ENABLE_DRIVER_USB_RP && MG_ENABLE_USB_ETHERNET + +extern struct mg_tcpip_driver mg_tcpip_driver_usb_rp; + +// Set MG_TCPIP_IP to give the device a static address and serve DHCP to the +// USB host. Leave it unset to get an address over DHCP, e.g. from macOS +// Internet Sharing. The device MAC comes from MG_SET_MAC_ADDRESS, random if +// it is not set; the host end of the link gets a MAC derived from it +#define MG_TCPIP_DRIVER_INIT(mgr) \ + do { \ + static struct mg_tcpip_if mif_; \ + mif_.ip = MG_TCPIP_IP; \ + mif_.mask = MG_TCPIP_MASK; \ + mif_.gw = MG_TCPIP_GW; \ + mif_.enable_dhcp_server = mif_.ip != 0; \ + mif_.driver = &mg_tcpip_driver_usb_rp; \ + mif_.recv_queue.size = MG_USB_QUEUE_SIZE; \ + MG_SET_MAC_ADDRESS(mif_.mac); \ + mg_tcpip_init(mgr, &mif_); \ + MG_INFO(("Driver: usb_rp, MAC: %M", mg_print_mac, mif_.mac)); \ + } while (0) + +#endif + + #if MG_ENABLE_TCPIP && defined(MG_ENABLE_DRIVER_W5100) && \ MG_ENABLE_DRIVER_W5100 diff --git a/src/arch_picosdk.h b/src/arch_picosdk.h index fc90c41c..ee932866 100644 --- a/src/arch_picosdk.h +++ b/src/arch_picosdk.h @@ -12,22 +12,23 @@ #include #include -#include +#include #include +#include #include int mkdir(const char *, mode_t); #if MG_OTA == MG_OTA_PICOSDK #include -#include #include +#include #include #ifndef MG_OTA_WATCHDOG_MS #if PICO_RP2040 -#define MG_OTA_WATCHDOG_MS 8000U // max delay on RP2040 is 8.3 seconds +#define MG_OTA_WATCHDOG_MS 8000U // max delay on RP2040 is 8.3 seconds #else -#define MG_OTA_WATCHDOG_MS 10000U // max delay on RP2350 is 16 seconds +#define MG_OTA_WATCHDOG_MS 10000U // max delay on RP2350 is 16 seconds #endif #endif @@ -44,17 +45,17 @@ int mkdir(const char *, mode_t); (watchdog_hw->scratch[0] = (uint32_t) (v), (uint32_t) watchdog_hw->scratch[0]) #if PICO_RP2040 -#define MG_OTA_ROLLBACK() \ - do { \ - mg_flash->swap_fn(); \ - *(volatile unsigned long *) 0xe000ed0c = 0x5fa0004; \ +#define MG_OTA_ROLLBACK() \ + do { \ + mg_flash->swap_fn(); \ + *(volatile unsigned long *) 0xe000ed0c = 0x5fa0004; \ } while (0) #else -#define MG_OTA_ROLLBACK() \ - do { \ - mg_flash->swap_fn(); \ - ((rom_reboot_fn) rom_func_lookup(ROM_FUNC_REBOOT))( \ - BOOT_TYPE_NORMAL | 0x100, 1, 0, 0); \ +#define MG_OTA_ROLLBACK() \ + do { \ + mg_flash->swap_fn(); \ + ((rom_reboot_fn) rom_func_lookup(ROM_FUNC_REBOOT))( \ + BOOT_TYPE_NORMAL | 0x100, 1, 0, 0); \ } while (0) #endif #endif diff --git a/src/config.h b/src/config.h index 30ebff28..d8913264 100644 --- a/src/config.h +++ b/src/config.h @@ -183,6 +183,26 @@ #define MG_ENABLE_TCPIP_TCPRTX 0 // TCP retransmission queue #endif +#ifndef MG_ENABLE_DRIVER_USB_RP +#define MG_ENABLE_DRIVER_USB_RP 0 // USB device, RP2040 / RP2350 +#endif + +#ifndef MG_ENABLE_DRIVER_USB_SAMD21 +#define MG_ENABLE_DRIVER_USB_SAMD21 0 // USB device, SAMD21 +#endif + +#ifndef MG_ENABLE_DRIVER_USB_NRF52 +#define MG_ENABLE_DRIVER_USB_NRF52 0 // USB device, nRF52840 +#endif + +#ifndef MG_ENABLE_USB_ETHERNET +#define MG_ENABLE_USB_ETHERNET 0 // USB driver: CDC-NCM Ethernet interface +#endif + +#ifndef MG_ENABLE_USB_SERIAL +#define MG_ENABLE_USB_SERIAL 0 // USB driver: CDC-ACM serial log console +#endif + #ifndef MG_TCPIP_DHCPNAME_SIZE #define MG_TCPIP_DHCPNAME_SIZE 18 // struct mg_tcpip_if :: dhcp_name size #endif diff --git a/src/drivers/usb.c b/src/drivers/usb.c new file mode 100644 index 00000000..9990ee2b --- /dev/null +++ b/src/drivers/usb.c @@ -0,0 +1,299 @@ +#include "drivers/usb.h" +#include "net_builtin.h" + +#if MG_ENABLE_USB + +// Interfaces: NCM control and data 0/1 if enabled, then ACM control and data +#define MG_USB_SERIAL_IF (2 * MG_ENABLE_USB_ETHERNET) +#define MG_USB_NUM_IFS (2 * MG_ENABLE_USB_ETHERNET + 2 * MG_ENABLE_USB_SERIAL) +#define MG_USB_CONFIG_LEN \ + (9 + 85 * MG_ENABLE_USB_ETHERNET + 66 * MG_ENABLE_USB_SERIAL) +#if MG_ENABLE_USB_ETHERNET +#define MG_USB_PRODUCT "MongooseUsbEthernet" +#else +#define MG_USB_PRODUCT "MongooseUsbSerial" +#endif + +// 0xdead is our example VID, for development only +static const uint8_t s_device_desc[] = { + 18, 1, 1, 2, 0xef, 2, 1, 64, 0xde, 0xad, 0xe4, 0x40, 0, 1, 1, 2, 3, 1}; + +// NCM: endpoints 0x81, 0x02/0x82. ACM: endpoints 0x83, 0x04/0x84 +static const uint8_t s_config_desc[] = { + 9, 2, MG_USB_CONFIG_LEN, 0, MG_USB_NUM_IFS, 1, 0, 0x80, 50, // Config +#if MG_ENABLE_USB_ETHERNET + 8, 11, 0, 2, 2, 13, 0, 4, // NCM association + 9, 4, 0, 0, 1, 2, 13, 0, 4, // NCM control interface + 5, 0x24, 0, 0x20, 1, // CDC header + 5, 0x24, 6, 0, 1, // Union + 13, 0x24, 15, 5, 0, 0, 0, 0, 0xea, + 5, 0, 0, 0, // Eth, 1514 bytes + 6, 0x24, 0x1a, 0, 1, 0x21, // NCM 1.0 + 7, 5, 0x81, 3, 16, 0, 16, // Notification endpoint + 9, 4, 1, 0, 0, 10, 0, 1, 0, // Data interface, off + 9, 4, 1, 1, 2, 10, 0, 1, 0, // Data interface, on + 7, 5, 0x02, 2, 64, 0, 0, // Data OUT + 7, 5, 0x82, 2, 64, 0, 0, // Data IN +#endif +#if MG_ENABLE_USB_SERIAL + 8, 11, MG_USB_SERIAL_IF, 2, 2, 2, 1, 6, // ACM association + 9, 4, MG_USB_SERIAL_IF, 0, 1, 2, 2, 1, 6, // ACM control interface + 5, 0x24, 0, 0x20, 1, // CDC header + 5, 0x24, 1, 0, MG_USB_SERIAL_IF + 1, // Call management + 4, 0x24, 2, 2, // ACM + 5, 0x24, 6, MG_USB_SERIAL_IF, MG_USB_SERIAL_IF + 1, // Union + 7, 5, 0x83, 3, 16, 0, 16, // Notification endpoint + 9, 4, MG_USB_SERIAL_IF + 1, 0, 2, 10, 0, 0, 0, // Data interface + 7, 5, 0x04, 2, 64, 0, 0, // Data OUT + 7, 5, 0x84, 2, 64, 0, 0, // Data IN +#endif +}; + +// Endpoint addresses, for CLEAR_FEATURE(ENDPOINT_HALT) +static const uint8_t s_endpoints[] = { +#if MG_ENABLE_USB_ETHERNET + 0x81, 0x02, 0x82, +#endif +#if MG_ENABLE_USB_SERIAL + 0x83, 0x04, 0x84, +#endif +}; + +#if MG_ENABLE_USB_ETHERNET +// Windows 11 binds its NCM driver through a Microsoft OS 2.0 compatible ID +static const uint8_t s_ms_os_desc[] = { + 10, 0, 0, 0, 0, 0, 3, 6, 46, 0, // Set header, Windows 8.1+ + 8, 0, 1, 0, 0, 0, 36, 0, // Configuration subset + 8, 0, 2, 0, 0, 0, 28, 0, // Function subset, NCM + 20, 0, 3, 0, 'W', 'I', 'N', 'N', 'C', 'M', // Compatible ID + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0}; +static const uint8_t s_bos_desc[] = { + 5, 15, 33, 0, 1, 28, 16, 5, 0, 0xdf, + 0x60, 0xdd, 0xd8, 0x89, 0x45, 0xc7, 0x4c, 0x9c, 0xd2, 0x65, + 0x9d, 0x9e, 0x64, 0x8a, 0x9f, 0, 0, 3, 6, sizeof(s_ms_os_desc), + 0, 1, 0}; + +// GET_NTB_PARAMETERS reply: NTB16 only, same limits both ways +static const uint8_t s_ntb_params[] = { + 28, 0, 1, 0, MG_USB_NTB_SIZE & 255, MG_USB_NTB_SIZE >> 8, 0, 0, 4, 0, 0, 0, + 4, 0, 0, 0, MG_USB_NTB_SIZE & 255, MG_USB_NTB_SIZE >> 8, 0, 0, 4, 0, 0, 0, + 4, 0, 16, 0}; + +// Link notifications: speed 12 Mbit/s both ways, connected, disconnected +static const uint8_t s_speed[] = {0xa1, 0x2a, 0, 0, 0, 0, 8, 0, + 0, 0x1b, 0xb7, 0, 0, 0x1b, 0xb7, 0}; +static const uint8_t s_up[] = {0xa1, 0, 1, 0, 0, 0, 0, 0}; +static const uint8_t s_down[] = {0xa1, 0, 0, 0, 0, 0, 0, 0}; + +// Transfer block header for one frame: NTH16, NDP16 with one datagram at +// offset 30, so that the IP header after the 14-byte Ethernet header lands +// on a 4-byte boundary +static const uint8_t s_nth[30] = {'N', 'C', 'M', 'H', 12, 0, 0, 0, 0, 0, + 12, 0, 'N', 'C', 'M', '0', 16, 0, 0, 0, + 30, 0, 0, 0, 0, 0, 0, 0, 0, 0}; +#endif + +// Build string descriptor i in u->buf. Returns its length, 0 if none +static int string_desc(struct mg_usb *u, unsigned i) { + static const char *strings[] = { + NULL, "Mongoose", MG_USB_PRODUCT, NULL, + "USB Ethernet", NULL, "USB Serial"}; + const char *s = i < 7 ? strings[i] : NULL; +#if MG_ENABLE_USB_ETHERNET + char mac[13]; +#endif + size_t k, n; + if (i == 0) return u->buf[0] = 4, u->buf[1] = 3, u->buf[2] = 9, u->buf[3] = 4; + if (i == 3) s = u->serial; +#if MG_ENABLE_USB_ETHERNET + if (i == 5) { // Host end of the link: the device MAC, first byte changed + uint8_t *m = u->ifp->mac; + mg_snprintf(mac, sizeof(mac), "%02X%02X%02X%02X%02X%02X", + ((m[0] ^ 4) | 2) & ~1, m[1], m[2], m[3], m[4], m[5]); + s = mac; + } +#endif + if (s == NULL) return 0; + n = strlen(s) > 32 ? 32 : strlen(s); + memset(u->buf, 0, sizeof(u->buf)); + for (k = 0; k < n; k++) u->buf[2 + k * 2] = (uint8_t) s[k]; + u->buf[0] = (uint8_t) (2 + n * 2), u->buf[1] = 3; + return u->buf[0]; +} + +void mg_usb_reset(struct mg_usb *u) { +#if MG_ENABLE_USB_SERIAL + static const uint8_t line[7] = {0, 0xc2, 1, 0, 0, 0, 8}; // 115200 8N1 + u->dtr = false; + memcpy(u->line, line, sizeof(line)); +#endif +#if MG_ENABLE_USB_ETHERNET + u->alt = false, u->filter = u->sequence = 0, u->notify = 0; + u->input_size = MG_USB_NTB_SIZE; +#endif + u->configured = false; +} + +int mg_usb_setup(struct mg_usb *u, const uint8_t *r, const void **reply) { + unsigned value = MG_LOAD_LE16(r + 2), index = MG_LOAD_LE16(r + 4); + unsigned wlen = MG_LOAD_LE16(r + 6); + const void *d = u->buf; + int n = 0; + switch ((r[0] << 8) | r[1]) { + case 0x8006: // GET_DESCRIPTOR + if (value >> 8 == 1) d = s_device_desc, n = sizeof(s_device_desc); + if (value >> 8 == 2) d = s_config_desc, n = sizeof(s_config_desc); +#if MG_ENABLE_USB_ETHERNET + if (value >> 8 == 15) d = s_bos_desc, n = sizeof(s_bos_desc); +#endif + if (value >> 8 == 3) n = string_desc(u, value & 255); + if (n == 0) return -1; + break; + case 0x0005: // SET_ADDRESS, applied by the driver after the status + if (value > 127) return -1; + break; + case 0x0009: // SET_CONFIGURATION + if (value > 1) return -1; + mg_usb_reset(u); + u->configured = value == 1; + break; + case 0x8008: // GET_CONFIGURATION + u->buf[0] = u->configured, n = 1; + break; + case 0x010b: // SET_INTERFACE: only the Ethernet data interface has 1 + if (index >= MG_USB_NUM_IFS || + value > (unsigned) (MG_ENABLE_USB_ETHERNET && index == 1)) + return -1; +#if MG_ENABLE_USB_ETHERNET + if (index == 1) u->alt = value == 1, u->notify = 1; +#endif + break; + case 0x810a: // GET_INTERFACE + u->buf[0] = 0, n = 1; +#if MG_ENABLE_USB_ETHERNET + if (index == 1) u->buf[0] = u->alt; +#endif + break; +#if MG_ENABLE_USB_ETHERNET + case 0xa183: // GET_NTB_FORMAT: NTB16 +#endif + case 0x8000: // GET_STATUS: device, interface, endpoint + case 0x8100: + case 0x8200: + u->buf[0] = u->buf[1] = 0, n = 2; + break; + case 0x0201: // CLEAR_FEATURE(ENDPOINT_HALT), applied by the driver + if (value || index > 255 || + !memchr(s_endpoints, (int) index, sizeof(s_endpoints))) + return -1; + break; +#if MG_ENABLE_USB_ETHERNET + case 0xc001: // Microsoft OS 2.0 descriptor set + if (index != 7) return -1; + d = s_ms_os_desc, n = sizeof(s_ms_os_desc); + break; + case 0x2143: // SET_ETHERNET_PACKET_FILTER + u->filter = (uint16_t) value; + break; + case 0xa180: // GET_NTB_PARAMETERS + d = s_ntb_params, n = sizeof(s_ntb_params); + break; + case 0x2184: // SET_NTB_FORMAT: NTB16 only + if (value) return -1; + break; + case 0xa185: // GET_NTB_INPUT_SIZE, one datagram per block + memset(u->buf, 0, 8); + MG_STORE_LE32(u->buf, u->input_size); + u->buf[4] = 1, n = 8; + break; + case 0x2186: // SET_NTB_INPUT_SIZE + if ((wlen != 4 && wlen != 8) || MG_LOAD_LE32(r + 8) < 2048 || + MG_LOAD_LE32(r + 8) > 65535) + return -1; + u->input_size = MG_LOAD_LE32(r + 8); + if (u->input_size > MG_USB_NTB_SIZE) u->input_size = MG_USB_NTB_SIZE; + break; +#endif +#if MG_ENABLE_USB_SERIAL + case 0xa121: // GET_LINE_CODING + d = u->line, n = sizeof(u->line); + break; + case 0x2120: // SET_LINE_CODING + if (wlen != sizeof(u->line)) return -1; + memcpy(u->line, r + 8, sizeof(u->line)); + break; + case 0x2122: // SET_CONTROL_LINE_STATE. Closed at 1200 baud: bootloader, + u->dtr = value & 1; // after a delay that lets this request complete + if (!u->dtr && MG_LOAD_LE32(u->line) == 1200) + u->reboot = mg_millis() + 100; + break; + case 0x2123: // SEND_BREAK + break; +#endif + default: + return -1; + } + *reply = d; + return n > (int) wlen ? (int) wlen : n; +} + +#if MG_ENABLE_USB_ETHERNET +size_t mg_usb_notify(struct mg_usb *u, const void **msg) { + if (!u->notify) return 0; + if (u->notify == 1 && u->alt) return u->notify = 2, *msg = s_speed, 16; + u->notify = 0, *msg = u->alt ? s_up : s_down; + return 8; +} + +size_t mg_usb_encode(struct mg_usb *u, uint8_t *p, const void *buf, + size_t len) { + if (!u->alt || !u->filter || len < 14 || len > 1514 || + len + 30 > u->input_size) + return 0; + memcpy(p, s_nth, sizeof(s_nth)); + MG_STORE_LE16(p + 6, u->sequence); + MG_STORE_LE16(p + 8, len + 30); + MG_STORE_LE16(p + 22, len); + memcpy(p + 30, buf, len); + u->sequence++; + return len + 30; +} + +// Offsets come from the host: bound every datagram by the block, and follow +// at most 16 datagram tables so that a cyclic chain cannot loop forever +void mg_usb_decode(struct mg_usb *u, const uint8_t *p, size_t len) { + size_t block, ndp, end, i, ofs, n, tables = 0; + if (len < 12 || MG_LOAD_LE32(p) != 0x484d434e) return; // "NCMH" + block = MG_LOAD_LE16(p + 8), ndp = MG_LOAD_LE16(p + 10); + if (block > len) return; + while (ndp && tables++ < 16 && ndp + 16 <= block && + MG_LOAD_LE32(p + ndp) == 0x304d434e) { // "NCM0" + end = ndp + MG_LOAD_LE16(p + ndp + 4); + for (i = ndp + 8; i + 4 <= end && end <= block; i += 4) { + ofs = MG_LOAD_LE16(p + i), n = MG_LOAD_LE16(p + i + 2); + if (ofs == 0 || n == 0) break; + if (n >= 14 && n <= 1514 && ofs + n <= block) + mg_tcpip_qwrite((void *) (p + ofs), n, u->ifp); + } + ndp = MG_LOAD_LE16(p + ndp + 6); + } +} +#endif + +#if MG_ENABLE_USB_SERIAL +void mg_usb_log(char ch, void *arg) { + struct mg_usb *u = (struct mg_usb *) arg; + if (u->head - u->tail >= MG_USB_LOG_SIZE) u->tail++; + u->log[u->head++ % MG_USB_LOG_SIZE] = ch; +} + +size_t mg_usb_log_read(struct mg_usb *u, void *buf, size_t len) { + size_t n = 0; + while (n < len && u->tail != u->head) { + ((char *) buf)[n++] = u->log[u->tail++ % MG_USB_LOG_SIZE]; + } + return n; +} +#endif + +#endif diff --git a/src/drivers/usb.h b/src/drivers/usb.h new file mode 100644 index 00000000..02879cd2 --- /dev/null +++ b/src/drivers/usb.h @@ -0,0 +1,96 @@ +#pragma once + +// USB device, independent of the controller: CDC-NCM Ethernet, enabled by +// MG_ENABLE_USB_ETHERNET, and a CDC-ACM serial port that carries the +// Mongoose log, enabled by MG_ENABLE_USB_SERIAL. The controller drivers +// are usb_rp.c, usb_samd21.c and usb_nrf52.c, enabled by +// MG_ENABLE_DRIVER_USB_*. Mongoose runs USB from mg_tcpip_init() and +// mg_mgr_poll(), so user code needs no USB calls + +#if MG_ENABLE_TCPIP && \ + (MG_ENABLE_DRIVER_USB_RP || MG_ENABLE_DRIVER_USB_SAMD21 || \ + MG_ENABLE_DRIVER_USB_NRF52) && \ + (MG_ENABLE_USB_ETHERNET || MG_ENABLE_USB_SERIAL) +#define MG_ENABLE_USB 1 + +// #if defined(MG_ENABLE_DRIVER_USB_SAMD21) && MG_ENABLE_DRIVER_USB_SAMD21 +// #define MG_USB_DEFAULT_SIZE 2048 // SAMD21: 32k RAM +// #else +// #define MG_USB_DEFAULT_SIZE 4096 +// #endif +#define MG_USB_DEFAULT_SIZE 2048 +#ifndef MG_USB_NTB_SIZE // Transfer block buffer, each direction, >= 2048 +#define MG_USB_NTB_SIZE MG_USB_DEFAULT_SIZE +#endif +#ifndef MG_USB_LOG_SIZE // Serial log ring buffer +#define MG_USB_LOG_SIZE (MG_USB_DEFAULT_SIZE / 2) +#endif +#ifndef MG_USB_QUEUE_SIZE // TCP/IP stack receive queue +#define MG_USB_QUEUE_SIZE (MG_USB_DEFAULT_SIZE * 2) +#endif + +// Endpoints: 1 interrupt IN, link notifications. 2 bulk IN/OUT, Ethernet. +// 3 interrupt IN, serial notifications (unused). 4 bulk IN/OUT, serial + +struct mg_usb { + const char *serial; // USB serial number, set by the driver + bool configured; // Host has set the configuration + uint8_t buf[66]; // Generated replies +#if MG_ENABLE_USB_ETHERNET + struct mg_tcpip_if *ifp; // TCP/IP interface, set by the driver + bool alt; // Ethernet open: data interface setting 1 + uint16_t filter, sequence; // Host packet filter, next IN block number + uint32_t input_size; // Largest IN block the host accepts + uint8_t notify; // Pending link notifications +#endif +#if MG_ENABLE_USB_SERIAL + bool dtr; // Terminal open + uint64_t reboot; // mg_millis() to enter the bootloader, or 0 + uint8_t line[7]; // Serial line coding + char log[MG_USB_LOG_SIZE]; // Serial log ring buffer + unsigned head, tail; // Log ring write and read counters +#endif +}; + +// Implemented by the enabled controller driver. Start the controller, once, +// and send the log to the serial port +void mg_usb_init(void); + +// Implemented by the enabled controller driver. Run the controller. Calls +// mg_usb_init() first, so it works without a TCP/IP interface too +void mg_usb_poll(void); + +// Unconfigured state, on start and after a bus reset. Keeps the log +void mg_usb_reset(struct mg_usb *u); + +// Handle an 8-byte SETUP packet, followed by its OUT data stage if it has +// one. Returns -1 to stall, else the IN reply length, 0 for status only +int mg_usb_setup(struct mg_usb *u, const uint8_t *req, const void **reply); + +#if MG_ENABLE_USB_ETHERNET +// Next link notification for endpoint 1. Returns its length, 0 if none +size_t mg_usb_notify(struct mg_usb *u, const void **msg); + +// Wrap an Ethernet frame into a transfer block at ntb. Returns the block +// length, 0 if the link is down or the frame does not fit +size_t mg_usb_encode(struct mg_usb *u, uint8_t *ntb, const void *buf, + size_t len); + +// Queue the Ethernet frames of a received transfer block to the TCP/IP stack +void mg_usb_decode(struct mg_usb *u, const uint8_t *ntb, size_t len); +#endif + +#if MG_ENABLE_USB_SERIAL +// Log output function for mg_log_set_fn(mg_usb_log, u). Keeps the latest +// MG_USB_LOG_SIZE characters +void mg_usb_log(char ch, void *u); + +// Take up to len logged characters into buf. Returns how many +size_t mg_usb_log_read(struct mg_usb *u, void *buf, size_t len); +#endif + +#else +#define MG_ENABLE_USB 0 +#define mg_usb_init() +#define mg_usb_poll() +#endif diff --git a/src/drivers/usb_nrf52.c b/src/drivers/usb_nrf52.c new file mode 100644 index 00000000..1b938865 --- /dev/null +++ b/src/drivers/usb_nrf52.c @@ -0,0 +1,337 @@ +#include "drivers/usb.h" +#include "drivers/usb_nrf52.h" +#include "net_builtin.h" + +#if MG_ENABLE_USB && MG_ENABLE_DRIVER_USB_NRF52 +#include + +// nRF52840 USB device controller, polled, full speed. Endpoint buffers are +// inside the controller: EasyDMA moves each packet between them and RAM, +// one transfer at a time, so longer IN transfers go out 64 bytes at a time. +// EasyDMA reads RAM only, thus constant data is copied to RAM first. The +// controller handles SET_ADDRESS by itself. Errata workarounds follow +// Nordic's nrfx_usbd.c: 171, 187 when enabling, 199 around each DMA + +#define ERRATA_199 (*(volatile uint32_t *) 0x40027c1c) + +struct nrf_in { // IN transfer on an endpoint + const uint8_t *data; // Bytes still to send, in RAM + size_t left; // How many + unsigned packets; // Packets still to send + bool busy; // A packet is waiting for the host +}; + +static struct nrf_in s_in[5]; // Index: endpoint number +static struct mg_usb s_usb; +static uint8_t s_req[16]; // SETUP packet, then its OUT data stage +static uint32_t s_ep0[256 / 4]; // Control IN reply, OUT data stage +static char s_serial[17]; // Serial number: device ID in hex +#if MG_ENABLE_USB_ETHERNET +static uint32_t s_note[16 / 4]; // Link notification +static uint32_t s_rx[MG_USB_NTB_SIZE / 4], s_tx[MG_USB_NTB_SIZE / 4]; +static size_t s_rxlen; // Received part of the OUT transfer block +static bool s_discard; // OUT transfer block too long: drop it +#endif +#if MG_ENABLE_USB_SERIAL +static uint32_t s_log[64 / 4]; // Log output in flight +#endif + +// Write an undocumented register the way Nordic's errata workarounds do +static void errata(uint32_t addr, uint32_t value) { + volatile uint32_t *unlock = (volatile uint32_t *) 0x4006ec00; + bool locked = *unlock == 0; + if (locked) *unlock = 0x9375; + *(volatile uint32_t *) addr = value; + if (locked) *unlock = 0x9375; +} + +// Run one EasyDMA transfer and wait for its end event +static void dma(volatile uint32_t *task, volatile uint32_t *end) { + unsigned i; + *end = 0; + ERRATA_199 = 0x82; + *task = 1; + for (i = 0; *end == 0 && i < 100000; i++) (void) 0; // Microseconds + *end = 0; + ERRATA_199 = 0; +} + +// Send the next packet of the IN transfer on ep. False if it is over +static bool in_next(unsigned ep) { + struct nrf_in *e = &s_in[ep]; + size_t n = e->left > 64 ? 64 : e->left; + if (e->packets == 0) return false; + NRF_USBD->EPIN[ep].PTR = (uint32_t) (uintptr_t) e->data; + NRF_USBD->EPIN[ep].MAXCNT = (uint32_t) n; + dma(&NRF_USBD->TASKS_STARTEPIN[ep], &NRF_USBD->EVENTS_ENDEPIN[ep]); + e->data += n, e->left -= n, e->packets--; + return true; +} + +// Start an IN transfer from RAM. zlp: end a multiple of 64 bytes with an +// empty packet +static void in_start(unsigned ep, const void *data, size_t len, bool zlp) { + struct nrf_in *e = &s_in[ep]; + e->data = (const uint8_t *) data, e->left = len; + e->packets = (unsigned) (len / 64 + (len % 64 || len == 0 || zlp)); + e->busy = in_next(ep); +} + +// Data toggle of endpoint address ep back to DATA0 +static void dtoggle(unsigned ep) { + NRF_USBD->DTOGGLE = ep; // Select the endpoint, then set its toggle + NRF_USBD->DTOGGLE = (USBD_DTOGGLE_VALUE_Data0 << USBD_DTOGGLE_VALUE_Pos) | ep; +} + +#if MG_ENABLE_USB_ETHERNET +// Ethernet data endpoints idle, ready to receive +static void data_reset(void) { + dtoggle(0x02), dtoggle(0x82); + memset(&s_in[2], 0, sizeof(s_in[2])); + s_rxlen = 0, s_discard = false; + NRF_USBD->SIZE.EPOUT[2] = 0; // Drop any received packet, accept the next +} + +// A packet on the Ethernet OUT endpoint: add it to the transfer block. The +// endpoint accepts the next packet once this one is moved or dropped +static void rx(void) { + size_t n = NRF_USBD->SIZE.EPOUT[2]; + if (n > 0 && !s_discard && s_rxlen + n <= sizeof(s_rx)) { + uint8_t *p = (uint8_t *) s_rx + s_rxlen; + NRF_USBD->EPOUT[2].PTR = (uint32_t) (uintptr_t) p; + NRF_USBD->EPOUT[2].MAXCNT = (uint32_t) n; + dma(&NRF_USBD->TASKS_STARTEPOUT[2], &NRF_USBD->EVENTS_ENDEPOUT[2]); + s_rxlen += n; + } else { + s_discard = s_discard || n > 0; // An empty packet only ends the block + NRF_USBD->SIZE.EPOUT[2] = 0; + } + // At the advertised maximum OUT size, the host need not send a ZLP. + // Other transfers end with a short packet (including a ZLP) + if (n < 64 || s_rxlen == sizeof(s_rx)) { + if (!s_discard) mg_usb_decode(&s_usb, (uint8_t *) s_rx, s_rxlen); + s_rxlen = 0, s_discard = false; + } +} +#endif + +// Endpoints 1-4 on and idle if configured, else off +static void endpoints_reset(void) { + memset(s_in, 0, sizeof(s_in)); + NRF_USBD->EPINEN = 1, NRF_USBD->EPOUTEN = 1; + if (!s_usb.configured) return; +#if MG_ENABLE_USB_ETHERNET + NRF_USBD->EPINEN |= MG_BIT(1) | MG_BIT(2), NRF_USBD->EPOUTEN |= MG_BIT(2); + dtoggle(0x81); + data_reset(); +#endif +#if MG_ENABLE_USB_SERIAL + NRF_USBD->EPINEN |= MG_BIT(3) | MG_BIT(4), NRF_USBD->EPOUTEN |= MG_BIT(4); + dtoggle(0x83), dtoggle(0x04), dtoggle(0x84); + NRF_USBD->SIZE.EPOUT[4] = 0; +#endif +} + +// Run a complete control request: SETUP in s_req, then any OUT data +static void request(void) { + const void *reply; + unsigned wlen = MG_LOAD_LE16(s_req + 6); + int n = mg_usb_setup(&s_usb, s_req, &reply); + if (n < 0) { + NRF_USBD->TASKS_EP0STALL = 1; + return; + } + switch ((s_req[0] << 8) | s_req[1]) { + case 0x0009: // SET_CONFIGURATION + endpoints_reset(); + break; +#if MG_ENABLE_USB_ETHERNET + case 0x010b: // SET_INTERFACE + if (s_req[4] == 1) data_reset(); + break; +#endif + case 0x0201: // CLEAR_FEATURE(ENDPOINT_HALT) + dtoggle(s_req[4]); + NRF_USBD->EPSTALL = + (USBD_EPSTALL_STALL_UnStall << USBD_EPSTALL_STALL_Pos) | s_req[4]; + if (!(s_req[4] & 0x80)) NRF_USBD->SIZE.EPOUT[s_req[4] & 15] = 0; + break; + } + if ((s_req[0] & 0x80) && wlen) { // IN data stage. Largest reply: 160 + memcpy(s_ep0, reply, (size_t) n); + in_start(0, s_ep0, (size_t) n, n < (int) wlen); + } else { + NRF_USBD->TASKS_EP0STATUS = 1; + } +} + +// A SETUP packet: run it, or first receive its OUT data stage +static void setup(void) { + const volatile uint32_t *regs = &NRF_USBD->BMREQUESTTYPE; + unsigned i, wlen; + for (i = 0; i < 8; i++) s_req[i] = (uint8_t) regs[i]; + wlen = MG_LOAD_LE16(s_req + 6); + memset(&s_in[0], 0, sizeof(s_in[0])); // Cancels the previous transfer + if (s_req[0] == 0 && s_req[1] == 5) return; // SET_ADDRESS: hardware's + if ((s_req[0] & 0x80) || wlen == 0) { + request(); + } else if (wlen > sizeof(s_req) - 8) { + NRF_USBD->TASKS_EP0STALL = 1; + } else { + NRF_USBD->TASKS_EP0RCVOUT = 1; // Accept the OUT data stage + } +} + +// A control data stage packet: an IN one acknowledged, or an OUT one arrived +static void ep0_data(void) { + size_t n = NRF_USBD->SIZE.EPOUT[0]; + if (s_req[0] & 0x80) { + if (!in_next(0)) NRF_USBD->TASKS_EP0STATUS = 1; + } else if (n != MG_LOAD_LE16(s_req + 6)) { + NRF_USBD->TASKS_EP0STALL = 1; + } else { + NRF_USBD->EPOUT[0].PTR = (uint32_t) (uintptr_t) s_ep0; + NRF_USBD->EPOUT[0].MAXCNT = (uint32_t) n; + dma(&NRF_USBD->TASKS_STARTEPOUT[0], &NRF_USBD->EVENTS_ENDEPOUT[0]); + memcpy(s_req + 8, s_ep0, n); + request(); + } +} + +// Follow USB power: enable the controller when VBUS appears, attach to the +// bus once both are ready, and detach when VBUS goes. True while attached +static bool attach(void) { + uint32_t power = NRF_POWER->USBREGSTATUS; + if (!(power & POWER_USBREGSTATUS_VBUSDETECT_Msk)) { + if (NRF_USBD->ENABLE) { + NRF_USBD->USBPULLUP = 0, NRF_USBD->ENABLE = 0; + mg_usb_reset(&s_usb); + } + return false; + } + if (!NRF_USBD->ENABLE) { + errata(0x4006ed14, 3); // Errata 187 + errata(0x4006ec14, 0xc0); // Errata 171 + NRF_USBD->EVENTCAUSE = USBD_EVENTCAUSE_READY_Msk; + NRF_USBD->ENABLE = 1; + } + if (NRF_USBD->USBPULLUP) return true; + if (!(NRF_USBD->EVENTCAUSE & USBD_EVENTCAUSE_READY_Msk) || + !(power & POWER_USBREGSTATUS_OUTPUTRDY_Msk)) + return false; + NRF_USBD->EVENTCAUSE = USBD_EVENTCAUSE_READY_Msk; + errata(0x4006ec14, 0); + errata(0x4006ed14, 0); + NRF_USBD->USBPULLUP = 1; + return true; +} + +void mg_usb_init(void) { + static bool started; + uint32_t id[2], xtal = CLOCK_HFCLKSTAT_SRC_Msk | CLOCK_HFCLKSTAT_STATE_Msk; + if (started) return; + started = true; + id[0] = NRF_FICR->DEVICEID[0], id[1] = NRF_FICR->DEVICEID[1]; + mg_snprintf(s_serial, sizeof(s_serial), "%M", mg_print_hex, (int) sizeof(id), + (uint8_t *) id); + s_usb.serial = s_serial; + mg_usb_reset(&s_usb); +#if MG_ENABLE_USB_SERIAL + mg_log_set_fn(mg_usb_log, &s_usb); // Log to the USB serial port +#endif + if ((NRF_CLOCK->HFCLKSTAT & xtal) != xtal) { // USB needs the crystal + NRF_CLOCK->TASKS_HFCLKSTART = 1; + while ((NRF_CLOCK->HFCLKSTAT & xtal) != xtal) (void) 0; + } + // The controller itself starts in mg_usb_poll(), once USB power is there +} + +void mg_usb_poll(void) { + mg_usb_init(); +#if MG_ENABLE_USB_SERIAL + if (s_usb.reboot && mg_millis() > s_usb.reboot) { + NRF_POWER->GPREGRET = 0x57; // Adafruit bootloader: stay in DFU mode + NVIC_SystemReset(); + } +#endif + if (!attach()) return; + if (NRF_USBD->EVENTS_USBRESET) { + NRF_USBD->EVENTS_USBRESET = 0; + NRF_USBD->EVENTS_EP0DATADONE = NRF_USBD->EVENTS_EPDATA = 0; + NRF_USBD->EPDATASTATUS = NRF_USBD->EPDATASTATUS; + mg_usb_reset(&s_usb); + endpoints_reset(); + return; + } + if (NRF_USBD->EVENTS_EP0DATADONE) { // Before a new SETUP replaces s_req + NRF_USBD->EVENTS_EP0DATADONE = 0; + ep0_data(); + } + if (NRF_USBD->EVENTS_EP0SETUP) { + NRF_USBD->EVENTS_EP0SETUP = 0; + setup(); + } + if (NRF_USBD->EVENTS_EPDATA) { // Bit n: IN n acknowledged, 16+n: OUT n + uint32_t done = NRF_USBD->EPDATASTATUS; + unsigned i; + NRF_USBD->EVENTS_EPDATA = 0; + NRF_USBD->EPDATASTATUS = done; + for (i = 1; i < 5; i++) { + if (done & MG_BIT(i)) s_in[i].busy = in_next(i); + } +#if MG_ENABLE_USB_ETHERNET + if (done & MG_BIT(18)) rx(); +#endif +#if MG_ENABLE_USB_SERIAL + if (done & MG_BIT(20)) NRF_USBD->SIZE.EPOUT[4] = 0; // Serial: ignored +#endif + } +#if MG_ENABLE_USB_ETHERNET + { + const void *msg; + size_t n; + if (!s_in[1].busy && (n = mg_usb_notify(&s_usb, &msg)) > 0) { + memcpy(s_note, msg, n); + in_start(1, s_note, n, false); + } + } +#endif +#if MG_ENABLE_USB_SERIAL + if (s_usb.configured && s_usb.dtr && !s_in[4].busy) { + size_t n = mg_usb_log_read(&s_usb, s_log, sizeof(s_log)); + if (n > 0) in_start(4, s_log, n, true); + } +#endif +} + +#if MG_ENABLE_USB_ETHERNET +static bool mg_tcpip_driver_usb_nrf52_init(struct mg_tcpip_if *ifp) { + s_usb.ifp = ifp; // mg_tcpip_init() has started USB already + return true; +} + +static size_t mg_tcpip_driver_usb_nrf52_tx(const void *buf, size_t len, + struct mg_tcpip_if *ifp) { + // One frame can be in flight. Keep USB moving while waiting, but bound + // the wait if the host stops reading or the cable is gone + uint64_t until = mg_millis() + 20; + size_t n = 0; + while (s_in[2].busy && mg_millis() < until) mg_usb_poll(); + if (!s_in[2].busy) n = mg_usb_encode(&s_usb, (uint8_t *) s_tx, buf, len); + if (n) in_start(2, s_tx, n, n < s_usb.input_size); + (void) ifp; + return n ? len : 0; +} + +// USB itself runs from mg_mgr_poll(). Report the link: Ethernet open +static bool mg_tcpip_driver_usb_nrf52_poll(struct mg_tcpip_if *ifp, bool s1) { + (void) ifp; + return s1 && s_usb.alt && s_usb.filter; +} + +struct mg_tcpip_driver mg_tcpip_driver_usb_nrf52 = { + mg_tcpip_driver_usb_nrf52_init, mg_tcpip_driver_usb_nrf52_tx, NULL, + mg_tcpip_driver_usb_nrf52_poll}; +#endif + +#endif diff --git a/src/drivers/usb_nrf52.h b/src/drivers/usb_nrf52.h new file mode 100644 index 00000000..7efff6f0 --- /dev/null +++ b/src/drivers/usb_nrf52.h @@ -0,0 +1,34 @@ +#pragma once + +// nRF52840 USB device controller, see usb.h: CDC-NCM Ethernet and a CDC-ACM +// serial log console. No TinyUSB, polled. Needs the nRF52840 device headers +// from nrfx/mdk on the include path. Example: tutorials/nordic/xiao-52840 + +#if MG_ENABLE_USB && MG_ENABLE_DRIVER_USB_NRF52 && MG_ENABLE_USB_ETHERNET + +extern struct mg_tcpip_driver mg_tcpip_driver_usb_nrf52; + +// Set MG_TCPIP_IP to give the device a static address and serve DHCP to the +// USB host. Leave it unset to get an address over DHCP, e.g. from macOS +// Internet Sharing. The device MAC comes from MG_SET_MAC_ADDRESS, random if +// it is not set; the host end of the link gets a MAC derived from it +#define MG_TCPIP_DRIVER_USB_NRF52_INIT(mgr) \ + do { \ + static struct mg_tcpip_if mif_; \ + mif_.ip = MG_TCPIP_IP; \ + mif_.mask = MG_TCPIP_MASK; \ + mif_.gw = MG_TCPIP_GW; \ + mif_.enable_dhcp_server = mif_.ip != 0; \ + mif_.driver = &mg_tcpip_driver_usb_nrf52; \ + mif_.recv_queue.size = MG_USB_QUEUE_SIZE; \ + MG_SET_MAC_ADDRESS(mif_.mac); \ + mg_tcpip_init(mgr, &mif_); \ + MG_INFO(("Driver: usb_nrf52, MAC: %M", mg_print_mac, mif_.mac)); \ + } while (0) + +// Like nrf52.h: both nRF52 drivers can be enabled at once, e.g. in a bridge +#ifndef MG_TCPIP_DRIVER_INIT +#define MG_TCPIP_DRIVER_INIT(mgr) MG_TCPIP_DRIVER_USB_NRF52_INIT(mgr) +#endif + +#endif diff --git a/src/drivers/usb_rp.c b/src/drivers/usb_rp.c new file mode 100644 index 00000000..425932b0 --- /dev/null +++ b/src/drivers/usb_rp.c @@ -0,0 +1,320 @@ +#include "drivers/usb.h" +#include "drivers/usb_rp.h" +#include "net_builtin.h" + +#if MG_ENABLE_USB && MG_ENABLE_DRIVER_USB_RP + +// RP2040 / RP2350 USB device controller: single core, polled, full speed, +// 64-byte single-buffered endpoints in USB DPRAM. Longer IN transfers go +// out one packet at a time, the next one when the previous completes + +struct rp_ep { + uint8_t *buf; // Endpoint buffer in USB DPRAM + io_rw_32 *ctrl; // Buffer control register + const uint8_t *data; // IN transfer: bytes still to send + size_t left; // IN transfer: how many + unsigned packets; // IN transfer: packets still to send + uint8_t pid; // Next DATA PID, 0 or 1 + bool busy; // Buffer handed to the controller +}; + +static struct rp_ep s_ep[5][2]; // Index: endpoint number, OUT=0 IN=1 +static struct mg_usb s_usb; +static uint8_t s_req[16]; // SETUP packet, then its OUT data stage +static bool s_req_out; // Waiting for that OUT data stage +static uint8_t s_address; // Address to apply after the status stage +static char s_serial[2 * PICO_UNIQUE_BOARD_ID_SIZE_BYTES + 1]; +#if MG_ENABLE_USB_ETHERNET +static uint8_t s_rx[MG_USB_NTB_SIZE], s_tx[MG_USB_NTB_SIZE]; +static size_t s_rxlen; // Received part of the OUT transfer block +static bool s_discard; // OUT transfer block too long: drop it +#endif +#if MG_ENABLE_USB_SERIAL +static char s_log[64]; // Log output in flight +#endif + +// Hand one packet buffer to the controller. OUT: accept up to len bytes +static void packet(unsigned ep, bool in, const void *data, unsigned len) { + struct rp_ep *e = &s_ep[ep][in]; + uint32_t v = len | (e->pid ? USB_BUF_CTRL_DATA1_PID : 0) | + (in ? USB_BUF_CTRL_FULL : 0); + if (in && len) memcpy(e->buf, data, len); + e->pid ^= 1; + e->busy = true; + *e->ctrl = v; + // RP2040 datasheet: allow at least 12 cycles between writing buffer + // metadata and handing ownership to the controller through AVAIL + busy_wait_at_least_cycles(12); + *e->ctrl = v | USB_BUF_CTRL_AVAIL; +} + +// Send the next packet of the IN transfer on ep. False if it is over +static bool in_next(unsigned ep) { + struct rp_ep *e = &s_ep[ep][1]; + unsigned n = e->left > 64 ? 64 : (unsigned) e->left; + if (e->packets == 0) return false; + packet(ep, true, e->data, n); + e->data += n, e->left -= n, e->packets--; + return true; +} + +// Start an IN transfer. zlp: end a multiple of 64 bytes with an empty packet +static void in_start(unsigned ep, const void *data, size_t len, bool zlp) { + struct rp_ep *e = &s_ep[ep][1]; + e->data = (const uint8_t *) data, e->left = len; + e->packets = (unsigned) (len / 64 + (len % 64 || len == 0 || zlp)); + in_next(ep); +} + +// Set up endpoint ep, direction in, idle. Endpoints 1 and 3 are interrupt, +// 2 and 4 bulk, each with a 64-byte DPRAM buffer of its own +static void ep_init(unsigned ep, bool in) { + struct rp_ep *e = &s_ep[ep][in]; + e->ctrl = in ? &usb_dpram->ep_buf_ctrl[ep].in + : &usb_dpram->ep_buf_ctrl[ep].out; + e->buf = ep ? &usb_dpram->epx_data[(ep * 2 + in) * 64] : usb_dpram->ep0_buf_a; + e->pid = 0, e->busy = false, e->packets = 0; + *e->ctrl = 0; + if (ep) { + io_rw_32 *ctrl = in ? &usb_dpram->ep_ctrl[ep - 1].in + : &usb_dpram->ep_ctrl[ep - 1].out; + *ctrl = EP_CTRL_ENABLE_BITS | EP_CTRL_INTERRUPT_PER_BUFFER | + ((ep & 1 ? 3U : 2U) << EP_CTRL_BUFFER_TYPE_LSB) | + (uint32_t) ((uintptr_t) e->buf - (uintptr_t) usb_dpram); + } +} + +#if MG_ENABLE_USB_ETHERNET +// Ethernet data endpoints idle, then armed to receive if Ethernet is open +static void data_reset(void) { + ep_init(2, false), ep_init(2, true); + s_rxlen = 0, s_discard = false; + if (s_usb.alt) packet(2, false, NULL, 64); +} + +// A packet on the Ethernet OUT endpoint: add it to the transfer block +static void rx(const uint8_t *buf, unsigned n) { + if (s_rxlen + n <= sizeof(s_rx) && !s_discard) { + memcpy(s_rx + s_rxlen, buf, n); + s_rxlen += n; + } else { + s_discard = true; + } + // At the advertised maximum OUT size, the host need not send a ZLP. + // Other transfers end with a short packet (including a ZLP) + if (n < 64 || s_rxlen == sizeof(s_rx)) { + if (!s_discard) mg_usb_decode(&s_usb, s_rx, s_rxlen); + s_rxlen = 0; + s_discard = false; + } + if (s_usb.alt) packet(2, false, NULL, 64); +} +#endif + +// All endpoints idle, then the serial port armed to receive if configured +static void endpoints_reset(void) { + static const uint8_t eps[] = { + 0x00, 0x80, +#if MG_ENABLE_USB_ETHERNET + 0x81, +#endif +#if MG_ENABLE_USB_SERIAL + 0x83, 0x04, 0x84, +#endif + }; + size_t i; + for (i = 0; i < sizeof(eps); i++) ep_init(eps[i] & 15U, eps[i] >> 7); +#if MG_ENABLE_USB_ETHERNET + data_reset(); +#endif +#if MG_ENABLE_USB_SERIAL + if (s_usb.configured) packet(4, false, NULL, 64); +#endif +} + +// Stall endpoint 0 until the next SETUP +static void stall(void) { + usb_hw->ep_stall_arm = + USB_EP_STALL_ARM_EP0_IN_BITS | USB_EP_STALL_ARM_EP0_OUT_BITS; + *s_ep[0][1].ctrl = USB_BUF_CTRL_STALL; + *s_ep[0][0].ctrl = USB_BUF_CTRL_STALL; +} + +// Run a complete control request: SETUP in s_req, then any OUT data +static void request(void) { + const void *reply; + int n = mg_usb_setup(&s_usb, s_req, &reply); + if (n < 0) { + stall(); + return; + } + switch ((s_req[0] << 8) | s_req[1]) { + case 0x0005: // SET_ADDRESS, applied after the status stage + s_address = s_req[2]; + break; + case 0x0009: // SET_CONFIGURATION + endpoints_reset(); + break; +#if MG_ENABLE_USB_ETHERNET + case 0x010b: // SET_INTERFACE + if (s_req[4] == 1) data_reset(); + break; +#endif + case 0x0201: { // CLEAR_FEATURE(ENDPOINT_HALT) + struct rp_ep *e = &s_ep[s_req[4] & 15][s_req[4] >> 7]; + *e->ctrl &= ~USB_BUF_CTRL_STALL, e->pid = 0; + break; + } + } + // IN data stage, or the status stage, both starting with DATA1 + s_ep[0][1].pid = 1; + in_start(0, reply, (size_t) n, n < (int) MG_LOAD_LE16(s_req + 6)); +} + +// A SETUP packet: run it, or first receive its OUT data stage +static void setup(void) { + unsigned wlen; + memcpy(s_req, (const void *) usb_dpram->setup_packet, 8); + wlen = MG_LOAD_LE16(s_req + 6); + // A SETUP cancels the preceding control transfer. OUT stages use DATA1 + ep_init(0, false), ep_init(0, true); + s_ep[0][0].pid = 1; + s_address = 0, s_req_out = false; + if ((s_req[0] & 0x80) || wlen == 0) { + request(); + } else if (wlen > sizeof(s_req) - 8) { + stall(); + } else { + s_req_out = true; + packet(0, false, NULL, 64); + } +} + +// A buffer the controller has finished with +static void complete(unsigned ep, bool in) { + struct rp_ep *e = &s_ep[ep][in]; + unsigned n = *e->ctrl & USB_BUF_CTRL_LEN_MASK; + e->busy = false; + if (in && in_next(ep)) return; + if (ep == 0 && in) { // Control IN data or status stage sent + if (s_address) { + usb_hw->dev_addr_ctrl = s_address, s_address = 0; + } else if ((s_req[0] & 0x80) && MG_LOAD_LE16(s_req + 6)) { + packet(0, false, NULL, 64); // Host's OUT status stage + } + } else if (ep == 0 && !in && s_req_out) { // Control OUT data stage + s_req_out = false; + if (n != MG_LOAD_LE16(s_req + 6)) { + stall(); + } else { + memcpy(s_req + 8, e->buf, n); + request(); + } +#if MG_ENABLE_USB_ETHERNET + } else if (ep == 2 && !in) { + rx(e->buf, n); +#endif +#if MG_ENABLE_USB_SERIAL + } else if (ep == 4 && !in) { + packet(4, false, NULL, 64); // Serial input is discarded: log console +#endif + } +} + +void mg_usb_init(void) { + static bool started; + if (started) return; + started = true; + pico_get_unique_board_id_string(s_serial, sizeof(s_serial)); + s_usb.serial = s_serial; + mg_usb_reset(&s_usb); +#if MG_ENABLE_USB_SERIAL + mg_log_set_fn(mg_usb_log, &s_usb); // Log to the USB serial port +#endif + reset_block(RESETS_RESET_USBCTRL_BITS); + unreset_block_wait(RESETS_RESET_USBCTRL_BITS); + memset(usb_dpram, 0, sizeof(*usb_dpram)); + usb_hw->muxing = USB_USB_MUXING_TO_PHY_BITS | USB_USB_MUXING_SOFTCON_BITS; + usb_hw->pwr = + USB_USB_PWR_VBUS_DETECT_BITS | USB_USB_PWR_VBUS_DETECT_OVERRIDE_EN_BITS; + usb_hw->main_ctrl = USB_MAIN_CTRL_CONTROLLER_EN_BITS; + usb_hw->sie_ctrl = USB_SIE_CTRL_EP0_INT_1BUF_BITS; + usb_hw->inte = 0; // Poll raw status instead of an interrupt handler + endpoints_reset(); + hw_set_bits(&usb_hw->sie_ctrl, USB_SIE_CTRL_PULLUP_EN_BITS); +} + +void mg_usb_poll(void) { + uint32_t status, done; + unsigned i; + mg_usb_init(); + status = usb_hw->intr; +#if MG_ENABLE_USB_SERIAL + if (s_usb.reboot && mg_millis() > s_usb.reboot) reset_usb_boot(0, 0); +#endif + if (status & USB_INTR_BUS_RESET_BITS) { + usb_hw->sie_status = USB_SIE_STATUS_BUS_RESET_BITS; + usb_hw->dev_addr_ctrl = 0; + usb_hw->buf_status = 0xffffffff; + mg_usb_reset(&s_usb); + endpoints_reset(); + return; + } + if (status & USB_INTR_SETUP_REQ_BITS) { + // Discard stale EP0 completions from an interrupted control transfer + usb_hw->buf_status = 3; + usb_hw->sie_status = USB_SIE_STATUS_SETUP_REC_BITS; + setup(); + } + done = usb_hw->buf_status; + for (i = 0; i < 10; i++) { // Bits: EP0 IN, EP0 OUT, EP1 IN, ... + if (!(done & (1U << i))) continue; + usb_hw->buf_status = 1U << i; + if (s_ep[i / 2][!(i & 1)].ctrl) complete(i / 2, !(i & 1)); + } +#if MG_ENABLE_USB_ETHERNET + if (!s_ep[1][1].busy) { + const void *msg; + size_t n = mg_usb_notify(&s_usb, &msg); + if (n) in_start(1, msg, n, false); + } +#endif +#if MG_ENABLE_USB_SERIAL + if (s_usb.configured && s_usb.dtr && !s_ep[4][1].busy) { + size_t n = mg_usb_log_read(&s_usb, s_log, sizeof(s_log)); + if (n) in_start(4, s_log, n, true); + } +#endif +} + +#if MG_ENABLE_USB_ETHERNET +static bool mg_tcpip_driver_usb_rp_init(struct mg_tcpip_if *ifp) { + s_usb.ifp = ifp; // mg_tcpip_init() has started USB already + return true; +} + +static size_t mg_tcpip_driver_usb_rp_tx(const void *buf, size_t len, + struct mg_tcpip_if *ifp) { + // One frame can be in flight. Keep USB moving while waiting, but bound + // the wait if the host stops reading or the cable is gone + uint64_t until = mg_millis() + 20; + size_t n = 0; + while (s_ep[2][1].busy && mg_millis() < until) mg_usb_poll(); + if (!s_ep[2][1].busy) n = mg_usb_encode(&s_usb, s_tx, buf, len); + if (n) in_start(2, s_tx, n, n < s_usb.input_size); + (void) ifp; + return n ? len : 0; +} + +// USB itself runs from mg_mgr_poll(). Report the link: Ethernet open +static bool mg_tcpip_driver_usb_rp_poll(struct mg_tcpip_if *ifp, bool s1) { + (void) ifp; + return s1 && s_usb.alt && s_usb.filter; +} + +struct mg_tcpip_driver mg_tcpip_driver_usb_rp = { + mg_tcpip_driver_usb_rp_init, mg_tcpip_driver_usb_rp_tx, NULL, + mg_tcpip_driver_usb_rp_poll}; +#endif + +#endif diff --git a/src/drivers/usb_rp.h b/src/drivers/usb_rp.h new file mode 100644 index 00000000..118214a4 --- /dev/null +++ b/src/drivers/usb_rp.h @@ -0,0 +1,28 @@ +#pragma once + +// RP2040 / RP2350 native USB controller, see usb.h: CDC-NCM Ethernet and +// a CDC-ACM serial log console. No TinyUSB, polled. Example: tutorials/rp/usb + +#if MG_ENABLE_USB && MG_ENABLE_DRIVER_USB_RP && MG_ENABLE_USB_ETHERNET + +extern struct mg_tcpip_driver mg_tcpip_driver_usb_rp; + +// Set MG_TCPIP_IP to give the device a static address and serve DHCP to the +// USB host. Leave it unset to get an address over DHCP, e.g. from macOS +// Internet Sharing. The device MAC comes from MG_SET_MAC_ADDRESS, random if +// it is not set; the host end of the link gets a MAC derived from it +#define MG_TCPIP_DRIVER_INIT(mgr) \ + do { \ + static struct mg_tcpip_if mif_; \ + mif_.ip = MG_TCPIP_IP; \ + mif_.mask = MG_TCPIP_MASK; \ + mif_.gw = MG_TCPIP_GW; \ + mif_.enable_dhcp_server = mif_.ip != 0; \ + mif_.driver = &mg_tcpip_driver_usb_rp; \ + mif_.recv_queue.size = MG_USB_QUEUE_SIZE; \ + MG_SET_MAC_ADDRESS(mif_.mac); \ + mg_tcpip_init(mgr, &mif_); \ + MG_INFO(("Driver: usb_rp, MAC: %M", mg_print_mac, mif_.mac)); \ + } while (0) + +#endif diff --git a/src/l2_eth.c b/src/l2_eth.c index 0d30b9b5..32fd4ab1 100644 --- a/src/l2_eth.c +++ b/src/l2_eth.c @@ -94,13 +94,6 @@ size_t mg_l2_eth_trailer(struct mg_tcpip_if *ifp, size_t len, uint8_t *cur) { struct mg_l2addr *mg_l2_eth_mapip(enum mg_l2addrtype addrtype, struct mg_addr *addr); -// Read an unaligned little-endian value from byte pointer p into a native integer. -// Safe on architectures that forbid unaligned access (e.g. Cortex-M0). -#define MG_LOAD_LE32(p) \ - ((uint32_t) (((uint32_t) MG_U8P(p)[3] << 24U) | \ - ((uint32_t) MG_U8P(p)[2] << 16U) | \ - ((uint32_t) MG_U8P(p)[1] << 8U) | MG_U8P(p)[0])) - bool mg_l2_eth_rx(struct mg_tcpip_if *ifp, enum mg_l2proto *proto, struct mg_str *pay, struct mg_str *raw) { struct eth *eth = (struct eth *) raw->buf; diff --git a/src/net_builtin.c b/src/net_builtin.c index 9db296be..1b2bfc04 100644 --- a/src/net_builtin.c +++ b/src/net_builtin.c @@ -1,5 +1,6 @@ #include "net_builtin.h" #include "bsd.h" +#include "drivers/usb.h" #include "mdash.h" #include "ota.h" #include "printf.h" @@ -2290,6 +2291,7 @@ void mg_tcpip_qwrite(void *buf, size_t len, struct mg_tcpip_if *ifp) { } void mg_tcpip_init(struct mg_mgr *mgr, struct mg_tcpip_if *ifp) { + mg_usb_init(); // Early, so that the log reaches the USB serial port // If L2 address is not set, make a random one; fill MTU mg_l2_init(ifp); ifp->mtu = ifp->l2mtu; @@ -2456,6 +2458,7 @@ void mg_mgr_poll(struct mg_mgr *mgr, int ms) { mg_timer_poll(&mgr->timers, now); mg_ota_poll(mgr); mg_mdash_poll(mgr); + mg_usb_poll(); // Also without a TCP/IP interface: USB serial only if (mgr->ifp == NULL || mgr->ifp->driver == NULL) return; mg_tcpip_poll(mgr->ifp, now); for (c = mgr->conns; c != NULL; c = tmp) { diff --git a/src/util.h b/src/util.h index d6ef816b..4815d5d3 100644 --- a/src/util.h +++ b/src/util.h @@ -136,6 +136,26 @@ uint64_t mg_timegm(unsigned int year, unsigned int month, unsigned int day, MG_U8P(p)[7] = (uint8_t) (n); \ } while (0) +// Little-endian counterparts, e.g. for USB. Safe for unaligned access +#define MG_LOAD_LE16(p) \ + ((uint16_t) (((uint16_t) MG_U8P(p)[1] << 8U) | MG_U8P(p)[0])) +#define MG_LOAD_LE32(p) \ + ((uint32_t) (((uint32_t) MG_U8P(p)[3] << 24U) | \ + ((uint32_t) MG_U8P(p)[2] << 16U) | \ + ((uint32_t) MG_U8P(p)[1] << 8U) | MG_U8P(p)[0])) +#define MG_STORE_LE16(p, n) \ + do { \ + MG_U8P(p)[0] = (uint8_t) (n); \ + MG_U8P(p)[1] = (uint8_t) ((n) >> 8U); \ + } while (0) +#define MG_STORE_LE32(p, n) \ + do { \ + MG_U8P(p)[0] = (uint8_t) (n); \ + MG_U8P(p)[1] = (uint8_t) ((n) >> 8U); \ + MG_U8P(p)[2] = (uint8_t) ((n) >> 16U); \ + MG_U8P(p)[3] = (uint8_t) ((n) >> 24U); \ + } while (0) + // Network / host byte-order conversion (big-endian <-> native). // mg_htons/mg_htonl/mg_htonll are aliases for the same operation (symmetric). uint16_t mg_ntohs(uint16_t net); diff --git a/tutorials/nordic/xiao-52840/minimal/Makefile b/tutorials/nordic/xiao-52840/minimal/Makefile index 121bcf92..455bda95 100644 --- a/tutorials/nordic/xiao-52840/minimal/Makefile +++ b/tutorials/nordic/xiao-52840/minimal/Makefile @@ -3,7 +3,8 @@ MGDIR = ../../../.. # Flash over USB: the board's Adafruit UF2 bootloader does serial DFU. The -# firmware resets into it on a 1200 baud touch, see usb.c. PORT: the board's +# firmware resets into it on a 1200 baud touch of its USB serial port, see +# Mongoose's src/drivers/usb_nrf52.c. PORT: the board's # USB serial port. adafruit-nrfutil: pip install adafruit-nrfutil PORT ?= /dev/cu.usbmodem11301 NRFUTIL ?= adafruit-nrfutil @@ -12,31 +13,25 @@ CFLAGS = -W -Wall -Wextra -Werror -Wshadow -Wdouble-promotion CFLAGS += -Wformat-truncation -fno-common -Wno-conversion -Wno-sign-conversion CFLAGS += -g3 -Os -ffunction-sections -fdata-sections CFLAGS += -I. -I$(MGDIR) -Icmsis_core/CMSIS/Core/Include -CFLAGS += -Inrfx/mdk -Inrfx -Inrfx/hal -Inrfx/templates -Inrfx/drivers/src -Itinyusb/src -CFLAGS += -Wno-cast-align -Wno-shadow -Wno-unused-parameter +CFLAGS += -Inrfx/mdk +CFLAGS += -Wno-shadow # src/drivers/nrf52.c, RADIO_IRQHandler(): dst CFLAGS += -DNRF52840_XXAA -D__STARTUP_CLEAR_BSS -D__START=main -D__HEAP_SIZE=0 CFLAGS += -mcpu=cortex-m4 -mthumb -mfloat-abi=hard -mfpu=fpv4-sp-d16 CFLAGS += $(CFLAGS_EXTRA) LDFLAGS ?= -Tlink.ld -nostdlib -nostartfiles --specs=nano.specs -lc -lm -lgcc -Wl,--gc-sections -SOURCES = main.c hal.c usb.c $(MGDIR)/mongoose.c +SOURCES = main.c hal.c $(MGDIR)/mongoose.c SOURCES += $(MGDIR)/tutorials/mqtt/mqtt-client/mongoose_mqtt.c SOURCES += nrfx/mdk/system_nrf52840.c nrfx/mdk/gcc_startup_nrf52840.S -# TinyUSB, for the USB serial console: the board has no USB-UART chip -SOURCES += tinyusb/src/tusb.c tinyusb/src/common/tusb_fifo.c -SOURCES += tinyusb/src/device/usbd.c tinyusb/src/device/usbd_control.c -SOURCES += tinyusb/src/class/cdc/cdc_device.c -SOURCES += tinyusb/src/portable/nordic/nrf5x/dcd_nrf5x.c - all build: firmware.hex firmware.hex: firmware.elf arm-none-eabi-objcopy -O ihex $< $@ arm-none-eabi-size --format=berkeley $< -firmware.elf: cmsis_core nrfx tinyusb $(SOURCES) $(wildcard *.h) link.ld Makefile +firmware.elf: cmsis_core nrfx $(SOURCES) $(wildcard *.h) link.ld Makefile arm-none-eabi-gcc $(SOURCES) $(CFLAGS) $(LDFLAGS) -o $@ firmware.zip: firmware.hex @@ -48,14 +43,12 @@ flash: firmware.zip cmsis_core: git clone -q -c advice.detachedHead=false --depth 1 -b 5.9.0 https://github.com/ARM-software/CMSIS_5 $@ -# nRF52840 device headers and SystemInit(), nrf_* register helpers for TinyUSB +# nRF52840 device headers, SystemInit() and the startup code nrfx: git clone -q -c advice.detachedHead=false --depth 1 -b v2.11.0 https://github.com/NordicSemiconductor/nrfx $@ -tinyusb: - git clone -q -c advice.detachedHead=false --depth 1 -b 0.14.0 https://github.com/hathach/tinyusb $@ clean: - rm -rf firmware.* *.dSYM tinyusb nrfx cmsis_core + rm -rf firmware.* *.dSYM nrfx cmsis_core .PHONY: all build flash clean diff --git a/tutorials/nordic/xiao-52840/minimal/hal.h b/tutorials/nordic/xiao-52840/minimal/hal.h index 85157db7..a333e33a 100644 --- a/tutorials/nordic/xiao-52840/minimal/hal.h +++ b/tutorials/nordic/xiao-52840/minimal/hal.h @@ -7,9 +7,6 @@ uint64_t hal_get_tick(void); bool hal_timer_expired(volatile uint64_t *t, uint64_t period, uint64_t now); size_t hal_ram_used(void); size_t hal_ram_free(void); -void usb_init(void); -void usb_poll(void); -void usb_log(char ch, void *param); #define BIT(x) (1UL << (x)) #define PIN(port, num) (((port) << 5) | (num)) diff --git a/tutorials/nordic/xiao-52840/minimal/main.c b/tutorials/nordic/xiao-52840/minimal/main.c index 3be71cb5..34cee6b4 100644 --- a/tutorials/nordic/xiao-52840/minimal/main.c +++ b/tutorials/nordic/xiao-52840/minimal/main.c @@ -6,10 +6,6 @@ #define LED1 PIN(0, 26) // P0.26, user LED, active low -static void log_fn(char ch, void *param) { - usb_log(ch, param); -} - static void blink_task(void) { static uint64_t blink_timer = 0; if (hal_timer_expired(&blink_timer, 500, hal_get_tick())) { @@ -75,14 +71,12 @@ int main(void) { MG_HEALTH_INIT(); hal_system_init(); - usb_init(); - mg_log_set_fn(log_fn, NULL); hal_rng_init(); hal_gpio_write(LED1, true); hal_gpio_output(LED1); struct mg_mgr mgr; - mg_mgr_init(&mgr); + mg_mgr_init(&mgr); // Also starts the radio and the USB log console mg_http_listen(&mgr, "http://0.0.0.0", http_ev_handler, NULL); mg_http_listen(&mgr, "https://0.0.0.0", http_ev_handler, NULL); mg_mqtt_init(&mgr); @@ -92,7 +86,6 @@ int main(void) { MG_INFO(("Crash record: %M", mg_print_crash_record)); for (;;) { - usb_poll(); mg_mgr_poll(&mgr, 0); mg_mqtt_poll(&mgr); blink_task(); diff --git a/tutorials/nordic/xiao-52840/minimal/mongoose_config.h b/tutorials/nordic/xiao-52840/minimal/mongoose_config.h index 5f8d9e56..eb6dedb9 100644 --- a/tutorials/nordic/xiao-52840/minimal/mongoose_config.h +++ b/tutorials/nordic/xiao-52840/minimal/mongoose_config.h @@ -2,7 +2,9 @@ #include "nrf.h" #define MG_ARCH MG_ARCH_ARMGCC #define MG_ENABLE_TCPIP 1 -#define MG_ENABLE_DRIVER_NRF52 1 +#define MG_ENABLE_DRIVER_NRF52 1 // 802.15.4 radio: the network interface +#define MG_ENABLE_DRIVER_USB_NRF52 1 // nRF52840 USB controller +#define MG_ENABLE_USB_SERIAL 1 // USB serial log console #define MG_ENABLE_TCPIP_TCPRTX 1 #define MG_ENABLE_CUSTOM_MICROS 1 #define MG_ENABLE_CUSTOM_RANDOM 1 diff --git a/tutorials/nordic/xiao-52840/minimal/tusb_config.h b/tutorials/nordic/xiao-52840/minimal/tusb_config.h deleted file mode 100644 index 4ca0c5cd..00000000 --- a/tutorials/nordic/xiao-52840/minimal/tusb_config.h +++ /dev/null @@ -1,9 +0,0 @@ -#pragma once -#define CFG_TUSB_MCU OPT_MCU_NRF5X -#define CFG_TUSB_OS OPT_OS_NONE -#define CFG_TUSB_RHPORT0_MODE OPT_MODE_DEVICE -#define CFG_TUD_ENDPOINT0_SIZE 64 -#define CFG_TUD_CDC 1 -#define CFG_TUD_CDC_RX_BUFSIZE 256 -#define CFG_TUD_CDC_TX_BUFSIZE 4096 -#define CFG_TUD_CDC_EP_BUFSIZE 64 diff --git a/tutorials/nordic/xiao-52840/minimal/usb.c b/tutorials/nordic/xiao-52840/minimal/usb.c deleted file mode 100644 index 90dd49cc..00000000 --- a/tutorials/nordic/xiao-52840/minimal/usb.c +++ /dev/null @@ -1,99 +0,0 @@ -#include "hal.h" -#include "tusb.h" -extern void tusb_hal_nrf_power_event(uint32_t event); -void USBD_IRQHandler(void) { - tud_int_handler(0); -} -void POWER_CLOCK_IRQHandler(void) { - if (NRF_POWER->EVENTS_USBDETECTED) { - NRF_POWER->EVENTS_USBDETECTED = 0; - tusb_hal_nrf_power_event(0); - } - if (NRF_POWER->EVENTS_USBREMOVED) { - NRF_POWER->EVENTS_USBREMOVED = 0; - tusb_hal_nrf_power_event(1); - } - if (NRF_POWER->EVENTS_USBPWRRDY) { - NRF_POWER->EVENTS_USBPWRRDY = 0; - tusb_hal_nrf_power_event(2); - } -} -void usb_init(void) { - NRF_POWER->INTENSET = POWER_INTENSET_USBDETECTED_Msk | - POWER_INTENSET_USBREMOVED_Msk | - POWER_INTENSET_USBPWRRDY_Msk; - NVIC_SetPriority(POWER_CLOCK_IRQn, 3); - NVIC_SetPriority(USBD_IRQn, 3); - if (NRF_POWER->USBREGSTATUS & POWER_USBREGSTATUS_VBUSDETECT_Msk) - tusb_hal_nrf_power_event(0); - if (NRF_POWER->USBREGSTATUS & POWER_USBREGSTATUS_OUTPUTRDY_Msk) - tusb_hal_nrf_power_event(2); - NRF_POWER->EVENTS_USBDETECTED = 0; - NRF_POWER->EVENTS_USBPWRRDY = 0; - NRF_POWER->EVENTS_USBREMOVED = 0; - NVIC_ClearPendingIRQ(POWER_CLOCK_IRQn); - tusb_init(); - NVIC_EnableIRQ(POWER_CLOCK_IRQn); -} -void usb_poll(void) { - tud_task(); - tud_cdc_write_flush(); -} -void usb_log(char ch, void *param) { - (void) param; - if (tud_cdc_connected()) tud_cdc_write_char(ch); -} -void tud_cdc_line_state_cb(uint8_t itf, bool dtr, bool rts) { - cdc_line_coding_t lc; - (void) rts; - tud_cdc_n_get_line_coding(itf, &lc); - if (!dtr && lc.bit_rate == 1200) { - NRF_POWER->GPREGRET = 0x57; - NVIC_SystemReset(); - } -} -static const tusb_desc_device_t s_dev = { - .bLength = sizeof(tusb_desc_device_t), - .bDescriptorType = TUSB_DESC_DEVICE, - .bcdUSB = 0x0200, - .bDeviceClass = TUSB_CLASS_MISC, - .bDeviceSubClass = MISC_SUBCLASS_COMMON, - .bDeviceProtocol = MISC_PROTOCOL_IAD, - .bMaxPacketSize0 = 64, - .idVendor = 0xcafe, - .idProduct = 0x4001, - .bcdDevice = 0x0100, - .iManufacturer = 1, - .iProduct = 2, - .iSerialNumber = 3, - .bNumConfigurations = 1}; -uint8_t const *tud_descriptor_device_cb(void) { - return (const uint8_t *) &s_dev; -} -static const uint8_t s_cfg[] = { - TUD_CONFIG_DESCRIPTOR(1, 2, 0, TUD_CONFIG_DESC_LEN + TUD_CDC_DESC_LEN, 0, - 100), - TUD_CDC_DESCRIPTOR(0, 0, 0x81, 8, 0x02, 0x82, 64)}; -uint8_t const *tud_descriptor_configuration_cb(uint8_t index) { - (void) index; - return s_cfg; -} -uint16_t const *tud_descriptor_string_cb(uint8_t index, uint16_t langid) { - static uint16_t buf[32]; - const char *strings[] = {"", "Cesanta", "XIAO nRF52840", "mongoose-nrf52840"}; - size_t n = 0; - (void) langid; - if (index == 0) { - buf[1] = 0x0409; - n = 1; - } else if (index < 4) { - const char *s = strings[index]; - while (s[n] && n < 31) { - buf[n + 1] = s[n]; - n++; - } - } else - return NULL; - buf[0] = (uint16_t) ((TUSB_DESC_STRING << 8) | (2 * n + 2)); - return buf; -} diff --git a/tutorials/nordic/xiao-52840/usb/Makefile b/tutorials/nordic/xiao-52840/usb/Makefile new file mode 100644 index 00000000..ec0bbf28 --- /dev/null +++ b/tutorials/nordic/xiao-52840/usb/Makefile @@ -0,0 +1,51 @@ +# Seeed XIAO nRF52840: Mongoose over USB CDC-NCM, no TinyUSB. +# Environment setup: https://mongoose.ws/documentation/tutorials/tools/ + +MGDIR = ../../../.. + +# Flash over USB: the board's Adafruit bootloader does serial DFU. The +# firmware reboots into it on a 1200 baud touch. PORT: the board's USB serial +# port. adafruit-nrfutil: pip install adafruit-nrfutil +PORT ?= /dev/cu.usbmodem11301 +NRFUTIL ?= adafruit-nrfutil + +CFLAGS = -W -Wall -Wextra -Werror -Wshadow -Wdouble-promotion +CFLAGS += -Wformat-truncation -fno-common -Wno-conversion -Wno-sign-conversion +CFLAGS += -g3 -Os -ffunction-sections -fdata-sections +CFLAGS += -I. -I$(MGDIR) -Icmsis_core/CMSIS/Core/Include -Inrfx/mdk +CFLAGS += -DNRF52840_XXAA -D__STARTUP_CLEAR_BSS -D__START=main -D__HEAP_SIZE=0 +CFLAGS += -mcpu=cortex-m4 -mthumb -mfloat-abi=hard -mfpu=fpv4-sp-d16 +CFLAGS += $(CFLAGS_EXTRA) + +LDFLAGS ?= -Tlink.ld -nostdlib -nostartfiles --specs=nano.specs -lc -lm -lgcc +LDFLAGS += -Wl,--gc-sections -Wl,-Map=$@.map + +SOURCES = hal.c main.c $(MGDIR)/mongoose.c +SOURCES += nrfx/mdk/system_nrf52840.c nrfx/mdk/gcc_startup_nrf52840.S + +all build: firmware.hex + +firmware.elf: cmsis_core nrfx $(SOURCES) $(wildcard *.h) link.ld Makefile + arm-none-eabi-gcc $(SOURCES) $(CFLAGS) $(LDFLAGS) -o $@ + arm-none-eabi-size --format=berkeley $@ + +firmware.hex: firmware.elf + arm-none-eabi-objcopy -O ihex $< $@ + +firmware.zip: firmware.hex + $(NRFUTIL) dfu genpkg --dev-type 0x0052 --sd-req 0xFFFE --application $< $@ + +flash: firmware.zip + $(NRFUTIL) dfu serial --package $< -p $(PORT) -b 115200 --singlebank --touch 1200 + +cmsis_core: + git clone -q -c advice.detachedHead=false --depth 1 -b 5.9.0 https://github.com/ARM-software/CMSIS_5 $@ + +# nRF52840 device headers, SystemInit() and the startup code +nrfx: + git clone -q -c advice.detachedHead=false --depth 1 -b v2.11.0 https://github.com/NordicSemiconductor/nrfx $@ + +clean: + rm -rf firmware.* cmsis_core nrfx + +.PHONY: all build flash clean diff --git a/tutorials/nordic/xiao-52840/usb/README.md b/tutorials/nordic/xiao-52840/usb/README.md new file mode 100644 index 00000000..feb23fbf --- /dev/null +++ b/tutorials/nordic/xiao-52840/usb/README.md @@ -0,0 +1,67 @@ +# XIAO nRF52840: USB Ethernet and serial with Mongoose + +One USB cable gives the board a CDC-NCM Ethernet interface and a CDC-ACM +serial port that carries the Mongoose log. The nRF52840 USB device controller +is driven directly: no TinyUSB, SoftDevice, Ethernet PHY, or lwIP. Mongoose +provides TCP/IP, a DHCP server, and HTTP/HTTPS servers. + +The USB code is a Mongoose driver, `src/drivers/usb_nrf52.c`. In +`mongoose_config.h`, `MG_ENABLE_DRIVER_USB_NRF52` selects it, and +`MG_ENABLE_USB_ETHERNET` and `MG_ENABLE_USB_SERIAL` turn on its two +functions. Mongoose runs it from `mg_mgr_init()` and `mg_mgr_poll()`, so +`main.c` only sets up the clock, the LED, and the HTTP listeners. + +## Build and flash + +Install the Arm GNU toolchain and `adafruit-nrfutil` +(`pip install adafruit-nrfutil`). The first build fetches CMSIS and Nordic's +nrfx, for the device headers and the startup code. + +```sh +make +make flash PORT=/dev/cu.usbmodemXXXX +``` + +The board keeps its Adafruit bootloader. The application starts at 0x27000, +above the area reserved for the SoftDevice, which is not used. `make flash` +opens the serial port at 1200 baud, which reboots the firmware into the +bootloader, then uploads over serial DFU. If no firmware with a USB serial +port is running, double-tap RESET to enter the bootloader first. + +## Use on macOS + +Connect with a USB data cable. macOS creates an Ethernet service and a +`/dev/cu.usbmodem*` serial port with built-in drivers. Allow the USB accessory +if prompted, and leave the network service set to DHCP. + +`mongoose_config.h` gives the device a static address, and the driver serves +DHCP to the host: + +* Device: `192.168.7.1/24` +* HTTP: +* HTTPS: (self-signed demonstration certificate) +* JSON tick: + +Change `MG_TCPIP_IP` and `MG_TCPIP_MASK` if the subnet conflicts with another +network. Remove them to make the board a DHCP client instead, for example +behind macOS Internet Sharing. + +```sh +curl --noproxy '*' http://192.168.7.1/api/tick +curl --noproxy '*' -k https://192.168.7.1/api/tick +screen /dev/cu.usbmodemXXXX 115200 +``` + +The baud rate is ignored, except that 1200 baud followed by DTR dropping +reboots into the bootloader. The serial port is an output console; received +bytes are discarded. + +## Implementation + +* `main.c`: LED blink task and the HTTP/HTTPS handler. +* `hal.h`, `hal.c`: clock, SysTick, RNG, LED, newlib stubs. +* `../../../../src/drivers/usb_nrf52.c`: nRF52840 USB device controller, + polled. EasyDMA moves each 64-byte packet, one transfer at a time. + Applies Nordic's errata 171, 187 and 199 workarounds. +* `../../../../src/drivers/usb.c`: controller independent NCM + ACM, shared + with the RP2040/RP2350 and SAMD21 drivers. diff --git a/tutorials/nordic/xiao-52840/usb/hal.c b/tutorials/nordic/xiao-52840/usb/hal.c new file mode 100644 index 00000000..42980ea6 --- /dev/null +++ b/tutorials/nordic/xiao-52840/usb/hal.c @@ -0,0 +1,109 @@ +// Copyright (c) 2026 Cesanta Software Limited +// All rights reserved + +#include "hal.h" +#include + +static volatile uint64_t s_ticks; // Milliseconds since boot +void SysTick_Handler(void) { // SysTick IRQ handler, triggered every 1ms + s_ticks++; +} + +uint64_t hal_get_tick(void) { + return s_ticks; +} + +// Mongoose time source, see MG_ENABLE_CUSTOM_MILLIS +uint64_t mg_millis(void) { + return s_ticks; +} + +// Mongoose random source, see MG_ENABLE_CUSTOM_RANDOM +bool mg_random(void *buf, size_t len) { + for (size_t n = 0; n < len; n += sizeof(uint32_t)) { + uint32_t r = hal_rng_read(); + memcpy((char *) buf + n, &r, n + sizeof(r) > len ? len - n : sizeof(r)); + } + return true; +} + +// Avoid pulling printf and friends in through assert() +void __assert_func(const char *s, int line, const char *fn, const char *expr) { + (void) s, (void) line, (void) fn, (void) expr; + for (;;) (void) 0; +} + +extern unsigned char _end[]; // End of data section, start of heap. See link.ld +static unsigned char *s_current_heap_end = _end; + +size_t hal_ram_used(void) { + return (size_t) (s_current_heap_end - _end); +} + +size_t hal_ram_free(void) { + unsigned char endofstack; + return (size_t) (&endofstack - s_current_heap_end); +} + +void *_sbrk(int incr) { + unsigned char *prev_heap; + unsigned char *heap_end = (unsigned char *) ((size_t) &heap_end - 256); + prev_heap = s_current_heap_end; + // Check how much space we got from the heap end to the stack end + if (s_current_heap_end + incr > heap_end) return (void *) -1; + s_current_heap_end += incr; + return prev_heap; +} + +// Newlib stubs +struct stat; +int _fstat(int fd, struct stat *st) { + (void) fd, (void) st; + return -1; +} + +int _open(const char *path) { + (void) path; + return -1; +} + +int _close(int fd) { + (void) fd; + return -1; +} + +int _isatty(int fd) { + (void) fd; + return 1; +} + +int _lseek(int fd, int ptr, int dir) { + (void) fd, (void) ptr, (void) dir; + return 0; +} + +void _exit(int status) { + (void) status; + for (;;) asm volatile("BKPT #0"); +} + +void _kill(int pid, int sig) { + (void) pid, (void) sig; +} + +int _getpid(void) { + return -1; +} + +int _write(int fd, char *ptr, int len) { + (void) fd, (void) ptr, (void) len; + return -1; +} + +int _read(int fd, char *ptr, int len) { + (void) fd, (void) ptr, (void) len; + return -1; +} + +void _init(void) { +} diff --git a/tutorials/nordic/xiao-52840/usb/hal.h b/tutorials/nordic/xiao-52840/usb/hal.h new file mode 100644 index 00000000..8a827a1b --- /dev/null +++ b/tutorials/nordic/xiao-52840/usb/hal.h @@ -0,0 +1,67 @@ +#pragma once +#include +#include +#include +#include "nrf.h" + +#define BIT(x) (1UL << (x)) +#define PIN(port, num) (((port) << 5) | (num)) +#define PINNO(pin) ((pin) & 31) +#define PINPORT(pin) ((pin) >> 5) +#define LED PIN(0, 26) // P0.26, red user LED, active low + +uint64_t hal_get_tick(void); +size_t hal_ram_used(void); +size_t hal_ram_free(void); + +static inline NRF_GPIO_Type *hal_gpio_bank(uint16_t pin) { + return PINPORT(pin) == 0 ? NRF_P0 : NRF_P1; +} + +static inline void hal_gpio_write(uint16_t pin, bool val) { + NRF_GPIO_Type *gpio = hal_gpio_bank(pin); + if (val) { + gpio->OUTSET = BIT(PINNO(pin)); + } else { + gpio->OUTCLR = BIT(PINNO(pin)); + } +} + +static inline void hal_gpio_toggle(uint16_t pin) { + hal_gpio_write(pin, (hal_gpio_bank(pin)->OUT & BIT(PINNO(pin))) == 0); +} + +static inline void hal_gpio_output(uint16_t pin) { + hal_gpio_bank(pin)->PIN_CNF[PINNO(pin)] = + (GPIO_PIN_CNF_DIR_Output << GPIO_PIN_CNF_DIR_Pos) | + (GPIO_PIN_CNF_INPUT_Disconnect << GPIO_PIN_CNF_INPUT_Pos); +} + +// Vectors above the bootloader, 64 MHz crystal clock, 1 ms SysTick +static inline void hal_system_init(void) { + extern uint32_t __isr_vector[]; + SCB->VTOR = (uint32_t) __isr_vector; + __DSB(); + __ISB(); + __enable_irq(); + NRF_CLOCK->EVENTS_HFCLKSTARTED = 0; + NRF_CLOCK->TASKS_HFCLKSTART = 1; + while (!NRF_CLOCK->EVENTS_HFCLKSTARTED) (void) 0; + SystemCoreClockUpdate(); + SysTick_Config(SystemCoreClock / 1000); +} + +static inline void hal_rng_init(void) { + NRF_RNG->CONFIG = 1; // Bias correction + NRF_RNG->TASKS_START = 1; +} + +static inline uint32_t hal_rng_read(void) { + uint32_t value = 0; + for (unsigned i = 0; i < 4; i++) { + while (!NRF_RNG->EVENTS_VALRDY) (void) 0; + value |= (uint32_t) NRF_RNG->VALUE << (i * 8); + NRF_RNG->EVENTS_VALRDY = 0; + } + return value; +} diff --git a/tutorials/nordic/xiao-52840/usb/link.ld b/tutorials/nordic/xiao-52840/usb/link.ld new file mode 100644 index 00000000..4c9448a2 --- /dev/null +++ b/tutorials/nordic/xiao-52840/usb/link.ld @@ -0,0 +1,62 @@ +/* nRF52840 on the XIAO nRF52840, with the Adafruit UF2 bootloader. Flash: + * MBR and SoftDevice S140 below 0x27000, the bootloader from 0xED000 up: the + * application in between. The SoftDevice is not enabled, so all RAM is ours, + * except the first 24k it would take: kept free, as the Arduino core does */ +ENTRY(Reset_Handler); +MEMORY { + flash(rx) : ORIGIN = 0x00027000, LENGTH = 0xC6000 + sram(rwx) : ORIGIN = 0x20006000, LENGTH = 0x3A000 +} + +SECTIONS { + .vectors : { KEEP(*(.isr_vector)) . = ALIGN(4); } > flash + .text : { *(.text* .text.*) } > flash + .rodata : { *(.rodata*) . = ALIGN(4); } > flash + + .data : { + _sdata = .; + *(.first_data) + *(.iram .iram.*) /* Mongoose MG_IRAM functions */ + *(.data SORT(.data.*)) + . = ALIGN(4); + _edata = .; + } > sram AT > flash + __data_start = _sdata; + __data_end = _edata; + __data_load_start = LOADADDR(.data); + /* Unused data regions expected by Nordic's standard startup. */ + __sdata_start = _edata; + __sdata_end = _edata; + __sdata_load_start = _edata; + __tdata_start = _edata; + __tdata_end = _edata; + __tdata_load_start = _edata; + __fast_start = _edata; + __fast_end = _edata; + __fast_load_start = _edata; + + .bss : { + _sbss = .; + *(.bss SORT(.bss.*) COMMON) + . = ALIGN(4); + _ebss = .; + } > sram + __bss_start__ = _sbss; + __bss_end__ = _ebss; + __tbss_start__ = _ebss; + __tbss_end__ = _ebss; + __sbss_start__ = _ebss; + __sbss_end__ = _ebss; + + /* Health record, see MG_HEALTH_RAM: not cleared, survives a warm reset */ + .mg_health (NOLOAD) : { KEEP(*(.mg_health .mg_health*)) } > sram + + . = ALIGN(8); + _end = .; /* Start of heap, see _sbrk() in hal.c */ + + /* Nordic startup reserves its default 16 KiB stack at the top of RAM. */ + .stack ORIGIN(sram) + LENGTH(sram) - 0x4000 (NOLOAD) : { + KEEP(*(.stack)) + } > sram + ASSERT(_end <= __StackLimit, "RAM sections overlap the stack") +} diff --git a/tutorials/nordic/xiao-52840/usb/main.c b/tutorials/nordic/xiao-52840/usb/main.c new file mode 100644 index 00000000..1a844dc5 --- /dev/null +++ b/tutorials/nordic/xiao-52840/usb/main.c @@ -0,0 +1,78 @@ +// Copyright (c) 2026 Cesanta Software Limited +// All rights reserved + +#include "hal.h" +#include "mongoose.h" + +static void blink_task(void) { + static uint64_t blink_timer = 0; + if (mg_timer_expired(&blink_timer, 500, mg_millis())) { + hal_gpio_toggle(LED); + } +} + +// Self-signed P-256 certificate and key for the HTTPS listener. Created by: +// openssl ecparam -genkey -name prime256v1 -noout -out key.pem +// openssl req -x509 -key key.pem -out cert.pem -days 3650 -subj /CN=mg +#define TLS_CERT \ + "-----BEGIN CERTIFICATE-----\n" \ + "MIIBgjCCASegAwIBAgIUIJOq77Qn7lHbH6WseMemeqorR50wCgYIKoZIzj0EAwIw\n" \ + "FjEUMBIGA1UEAwwLbnVjbGVvLWg3MjMwHhcNMjYxMDEyMTUwMjE5WhcNMzYxMDA5\n" \ + "MTUwMjE5WjAWMRQwEgYDVQQDDAtudWNsZW8taDcyMzBZMBMGByqGSM49AgEGCCqG\n" \ + "SM49AwEHA0IABB6IQJNmzrsdQL+2BnZYS7GYOaj7sz8f6cjBmz3n8D9Em19XodlU\n" \ + "uy4ybIvyhr766lL0ERoTmMUivb/lGmzx9C+jUzBRMB0GA1UdDgQWBBQqxMuc4gj7\n" \ + "MTMzreWlRMNI3QMqTzAfBgNVHSMEGDAWgBQqxMuc4gj7MTMzreWlRMNI3QMqTzAP\n" \ + "BgNVHRMBAf8EBTADAQH/MAoGCCqGSM49BAMCA0kAMEYCIQDY4xaJpuxq6b3rHK3b\n" \ + "lOIQyfkQX+orCRqQUkseplqpqwIhAKswZFNn+2zUNRRNY8+cHmdIwmdpsmxtoWYP\n" \ + "BCjX++LI\n" \ + "-----END CERTIFICATE-----\n" + +#define TLS_KEY \ + "-----BEGIN EC PRIVATE KEY-----\n" \ + "MHcCAQEEIJ/GBl0TlD52q9PMg1KWaNIdXqp8b/HyIsABmBpqC+O1oAoGCCqGSM49\n" \ + "AwEHoUQDQgAEHohAk2bOux1Av7YGdlhLsZg5qPuzPx/pyMGbPefwP0SbX1eh2VS7\n" \ + "LjJsi/KGvvrqUvQRGhOYxSK9v+UabPH0Lw==\n" \ + "-----END EC PRIVATE KEY-----\n" + +static void http_ev_handler(struct mg_connection *c, int ev, void *ev_data) { + if (ev == MG_EV_ACCEPT && c->is_tls) { // Accepted on the https:// listener + struct mg_tls_opts opts = {.cert = mg_str(TLS_CERT), + .key = mg_str(TLS_KEY)}; + mg_tls_init(c, &opts); + } else if (ev == MG_EV_HTTP_MSG) { + struct mg_http_message *hm = (struct mg_http_message *) ev_data; + if (mg_match(hm->uri, mg_str("/api/tick"), NULL)) { + mg_http_reply(c, 200, "", "{%m:%llu}\n", MG_ESC("tick"), mg_millis()); + } else { + mg_http_reply(c, 200, "", + "Hi from Mongoose!\n" + "tick: %llu\n" + "ram used: %zu\n" + "ram free: %zu\n", + mg_millis(), hal_ram_used(), hal_ram_free()); + } + } +} + +int main(void) { + hal_system_init(); + hal_rng_init(); + hal_gpio_write(LED, true); // Off + hal_gpio_output(LED); + + struct mg_mgr mgr; + mg_mgr_init(&mgr); // Also starts the USB driver, see mongoose_config.h + mg_http_listen(&mgr, "http://0.0.0.0", http_ev_handler, NULL); + mg_http_listen(&mgr, "https://0.0.0.0", http_ev_handler, NULL); + + MG_INFO(("Initialised. CPU clock: %lu MHz", SystemCoreClock / 1000000)); + MG_INFO(("RAM used: %zu, free: %zu", hal_ram_used(), hal_ram_free())); + MG_INFO(("USB Ethernet + serial")); + + for (;;) { + mg_mgr_poll(&mgr, 0); + blink_task(); + } + + return 0; +} diff --git a/tutorials/nordic/xiao-52840/usb/mongoose_config.h b/tutorials/nordic/xiao-52840/usb/mongoose_config.h new file mode 100644 index 00000000..bc9921b8 --- /dev/null +++ b/tutorials/nordic/xiao-52840/usb/mongoose_config.h @@ -0,0 +1,16 @@ +#pragma once +#define MG_ARCH MG_ARCH_ARMGCC +#define MG_TLS MG_TLS_BUILTIN +#define MG_ENABLE_TCPIP 1 +#define MG_ENABLE_IPV6 0 +#define MG_ENABLE_CUSTOM_MILLIS 1 +#define MG_ENABLE_CUSTOM_RANDOM 1 +#define MG_ENABLE_DRIVER_USB_NRF52 1 // nRF52840 USB controller +#define MG_ENABLE_USB_ETHERNET 1 // USB NCM Ethernet interface +#define MG_ENABLE_USB_SERIAL 1 // USB serial log console +// Static device address; the driver serves DHCP to the USB host. Remove +// these to get an address over DHCP instead, e.g. from Internet Sharing +#define MG_TCPIP_IP MG_IPV4(192, 168, 7, 1) +#define MG_TCPIP_MASK MG_IPV4(255, 255, 255, 0) +#define MG_SET_MAC_ADDRESS(mac) \ + do { mac[0] = 2; mac[1] = 3; mac[2] = 4; mac[3] = 5; mac[4] = 6; mac[5] = 7; } while (0) diff --git a/tutorials/rp/usb/CMakeLists.txt b/tutorials/rp/usb/CMakeLists.txt new file mode 100644 index 00000000..6630f4b6 --- /dev/null +++ b/tutorials/rp/usb/CMakeLists.txt @@ -0,0 +1,11 @@ +cmake_minimum_required(VERSION 3.13) +set(PICO_BOARD pico2 CACHE STRING "Target board") +include($ENV{PICO_SDK_PATH}/external/pico_sdk_import.cmake) +project(usb_ncm C CXX ASM) +pico_sdk_init() +add_executable(firmware main.c ../../../mongoose.c) +target_include_directories(firmware PRIVATE . ../../..) +target_link_libraries(firmware pico_stdlib pico_unique_id pico_rand hardware_resets) +pico_enable_stdio_usb(firmware 0) +pico_enable_stdio_uart(firmware 0) +pico_add_extra_outputs(firmware) diff --git a/tutorials/rp/usb/Makefile b/tutorials/rp/usb/Makefile new file mode 100644 index 00000000..03edda33 --- /dev/null +++ b/tutorials/rp/usb/Makefile @@ -0,0 +1,13 @@ +PICO_SDK_PATH ?= $(HOME)/src/pico-sdk +PICO_BOARD ?= pico2 +BUILD ?= build/$(PICO_BOARD) +.PHONY: all build flash clean +all: build +build: + PICO_SDK_PATH=$(PICO_SDK_PATH) cmake -S . -B $(BUILD) -DPICO_BOARD=$(PICO_BOARD) -DCMAKE_BUILD_TYPE=Release + cmake --build $(BUILD) -j 4 +flash: build + picotool load -f $(BUILD)/firmware.uf2 + picotool reboot +clean: + rm -rf build diff --git a/tutorials/rp/usb/README.md b/tutorials/rp/usb/README.md new file mode 100644 index 00000000..b6162e14 --- /dev/null +++ b/tutorials/rp/usb/README.md @@ -0,0 +1,99 @@ +# Pico 2 / XIAO RP2040: USB Ethernet and serial with Mongoose + +One USB cable gives the board a CDC-NCM Ethernet interface and a CDC-ACM +serial port that carries the Mongoose log. The native RP2040/RP2350 USB +controller is driven directly: no PIO, Ethernet PHY, TinyUSB, or lwIP. +Mongoose provides TCP/IP, a DHCP server, and HTTP/HTTPS servers. + +The USB code is a Mongoose driver, `src/drivers/usb_rp.c`, enabled by +`MG_ENABLE_DRIVER_USB_RP` in `mongoose_config.h`. `mg_mgr_init()` starts it, +so `main.c` only sets up the LED and the HTTP listeners. + +## Build and flash + +Install the Pico SDK, CMake, Arm GNU toolchain, and picotool. The Makefile +uses `~/src/pico-sdk`; override `PICO_SDK_PATH` if necessary. +The default target is `PICO_BOARD=pico2` (RP2350, Arm Cortex-M33). + +```sh +make # Pico 2 +make PICO_BOARD=seeed_xiao_rp2040 # XIAO RP2040 +``` + +Each board has its own build directory, `build/pico2/firmware.uf2` or +`build/seeed_xiao_rp2040/firmware.uf2`, so RP2040 and RP2350 CMake settings +never mix. + +On Pico 2, hold BOOTSEL while connecting the USB cable. On XIAO, hold BOOT +while pressing and releasing RESET, then release BOOT. Flash: + +```sh +make flash +``` + +The firmware also enters BOOTSEL when its serial port is opened at 1200 baud +and DTR drops. `picotool -f` alone cannot reboot it: the driver does not +implement the Pico SDK vendor reset interface. + +## Use on macOS + +Connect with a USB data cable. macOS creates an Ethernet service and a +`/dev/cu.usbmodem*` serial port with built-in drivers. Allow the USB accessory +if prompted, and leave the network service set to DHCP. + +`mongoose_config.h` gives the device a static address, and the driver serves +DHCP to the host: + +* Device: `192.168.7.1/24` +* HTTP: +* HTTPS: (self-signed demonstration certificate) +* JSON tick: + +Change `MG_TCPIP_IP` and `MG_TCPIP_MASK` if the subnet conflicts with another +network. Remove them to make the board a DHCP client instead, for example +behind macOS Internet Sharing. + +```sh +curl --noproxy '*' http://192.168.7.1/api/tick +curl --noproxy '*' -k https://192.168.7.1/api/tick +screen /dev/cu.usbmodemXXXX 115200 +``` + +Use the actual serial device path. The baud rate is ignored, except that +1200 baud followed by DTR dropping requests BOOTSEL. To exit screen, press +Ctrl-A, then backslash, and confirm. The serial port is an output console; +received bytes are discarded. + +Linux normally provides NCM and ACM drivers. Windows 11 provides NCM and ACM; +the driver includes Microsoft OS 2.0 compatible ID descriptors for driver +binding. Linux and Windows have not been tested here. Windows 10 has no +built-in NCM driver. + +## Implementation + +* `main.c`: LED blink task and the HTTP/HTTPS handler. +* `../../../src/drivers/usb_rp.c`: RP2040/RP2350 USB device controller. +* `../../../src/drivers/usb.c`: controller independent NCM + ACM: + descriptors, control requests, NTB16 negotiation, framing, parser, and the + serial log buffer. Shared with the SAMD21 driver, `usb_samd21.c`. +* Network control/data interfaces 0/1; ACM control/data interfaces 2/3. +* Network endpoints: interrupt IN 0x81, bulk OUT/IN 0x02/0x82. +* Serial endpoints: interrupt IN 0x83, bulk OUT/IN 0x04/0x84. +* Full-speed USB, 64-byte packets. Transfers span multiple packets and end + with short packets or ZLPs. Ethernet FCS is not sent on USB. +* NTB16 with no CRC, 4 KiB maximum IN/OUT blocks, and up to 16 incoming + datagrams per block, including chained NDPs. The whole block is validated + before any frame is delivered. NTB32 and CRC mode are not advertised. +* One Ethernet frame per outgoing block, within the host's negotiated input + size. Outgoing frames are not aggregated. +* Host and device MAC addresses and the USB serial number come from the + board's flash ID. One outgoing block can be in flight; incoming frames go + to Mongoose's 8 KiB queue. The serial log is a nonblocking 2 KiB ring; old + logs are overwritten when the host is not reading. +* Buffer sizes can be changed with `MG_USB_NCM_NTB_SIZE`, + `MG_USB_NCM_LOG_SIZE` and `MG_USB_NCM_QUEUE_SIZE`. +* Single core, polled from `mg_mgr_poll()`. No host mode, RNDIS, suspend, + remote wake, or Ethernet bridging. + +The development VID/PID is `CAFE:40E4`, not an allocation for shipped +products. Get a legitimate VID/PID before distributing hardware. diff --git a/tutorials/rp/usb/main.c b/tutorials/rp/usb/main.c new file mode 100644 index 00000000..24d6da75 --- /dev/null +++ b/tutorials/rp/usb/main.c @@ -0,0 +1,96 @@ +// Copyright (c) 2026 Cesanta Software Limited +// All rights reserved + +#include "hardware/clocks.h" +#include "mongoose.h" +#include "pico/stdlib.h" + +#define LED1 PICO_DEFAULT_LED_PIN // User LED, active low +//#define LED1 16 // User LED, active low + +static void blink_task(void) { + static uint64_t blink_timer = 0; + if (mg_timer_expired(&blink_timer, 500, mg_millis())) { + gpio_xor_mask(1u << LED1); + } +} + +// Match MG24's heap-extent measurements. The Pico SDK's newlib _sbrk(0) +// returns the current heap break without allocating. Its linker reserves +// stacks separately, so free space ends at __HeapLimit, not the current SP. +// These figures exclude globals/stacks and reusable blocks inside malloc. +extern void *_sbrk(int incr); +extern char __end__, __HeapLimit; + +static size_t hal_ram_used(void) { + return (size_t) ((uintptr_t) _sbrk(0) - (uintptr_t) &__end__); +} + +static size_t hal_ram_free(void) { + return (size_t) ((uintptr_t) &__HeapLimit - (uintptr_t) _sbrk(0)); +} + +// Self-signed P-256 certificate and key for the HTTPS listener. Created by: +// openssl ecparam -genkey -name prime256v1 -noout -out key.pem +// openssl req -x509 -key key.pem -out cert.pem -days 3650 -subj /CN=mg +#define TLS_CERT \ + "-----BEGIN CERTIFICATE-----\n" \ + "MIIBgjCCASegAwIBAgIUIJOq77Qn7lHbH6WseMemeqorR50wCgYIKoZIzj0EAwIw\n" \ + "FjEUMBIGA1UEAwwLbnVjbGVvLWg3MjMwHhcNMjYxMDEyMTUwMjE5WhcNMzYxMDA5\n" \ + "MTUwMjE5WjAWMRQwEgYDVQQDDAtudWNsZW8taDcyMzBZMBMGByqGSM49AgEGCCqG\n" \ + "SM49AwEHA0IABB6IQJNmzrsdQL+2BnZYS7GYOaj7sz8f6cjBmz3n8D9Em19XodlU\n" \ + "uy4ybIvyhr766lL0ERoTmMUivb/lGmzx9C+jUzBRMB0GA1UdDgQWBBQqxMuc4gj7\n" \ + "MTMzreWlRMNI3QMqTzAfBgNVHSMEGDAWgBQqxMuc4gj7MTMzreWlRMNI3QMqTzAP\n" \ + "BgNVHRMBAf8EBTADAQH/MAoGCCqGSM49BAMCA0kAMEYCIQDY4xaJpuxq6b3rHK3b\n" \ + "lOIQyfkQX+orCRqQUkseplqpqwIhAKswZFNn+2zUNRRNY8+cHmdIwmdpsmxtoWYP\n" \ + "BCjX++LI\n" \ + "-----END CERTIFICATE-----\n" + +#define TLS_KEY \ + "-----BEGIN EC PRIVATE KEY-----\n" \ + "MHcCAQEEIJ/GBl0TlD52q9PMg1KWaNIdXqp8b/HyIsABmBpqC+O1oAoGCCqGSM49\n" \ + "AwEHoUQDQgAEHohAk2bOux1Av7YGdlhLsZg5qPuzPx/pyMGbPefwP0SbX1eh2VS7\n" \ + "LjJsi/KGvvrqUvQRGhOYxSK9v+UabPH0Lw==\n" \ + "-----END EC PRIVATE KEY-----\n" + +static void http_ev_handler(struct mg_connection *c, int ev, void *ev_data) { + if (ev == MG_EV_ACCEPT && c->is_tls) { // Accepted on the https:// listener + struct mg_tls_opts opts = {.cert = mg_str(TLS_CERT), + .key = mg_str(TLS_KEY)}; + mg_tls_init(c, &opts); + } else if (ev == MG_EV_HTTP_MSG) { + struct mg_http_message *hm = (struct mg_http_message *) ev_data; + if (mg_match(hm->uri, mg_str("/api/tick"), NULL)) { + mg_http_reply(c, 200, "", "{%m:%llu}\n", MG_ESC("tick"), mg_millis()); + } else { + mg_http_reply(c, 200, "", + "Hi from Mongoose!\n" + "tick: %llu\n" + "ram used: %zu\n" + "ram free: %zu\n", + mg_millis(), hal_ram_used(), hal_ram_free()); + } + } +} + +int main(void) { + gpio_init(LED1); + gpio_put(LED1, 1); + gpio_set_dir(LED1, GPIO_OUT); + + struct mg_mgr mgr; + mg_mgr_init(&mgr); // Also starts the USB driver, see mongoose_config.h + mg_http_listen(&mgr, "http://0.0.0.0", http_ev_handler, NULL); + mg_http_listen(&mgr, "https://0.0.0.0", http_ev_handler, NULL); + + MG_INFO(("Initialised. CPU clock: %lu MHz", clock_get_hz(clk_sys) / 1000000)); + MG_INFO(("RAM used: %zu, free: %zu", hal_ram_used(), hal_ram_free())); + MG_INFO(("USB Ethernet + serial")); + + for (;;) { + mg_mgr_poll(&mgr, 0); + blink_task(); + } + + return 0; +} diff --git a/tutorials/rp/usb/mongoose_config.h b/tutorials/rp/usb/mongoose_config.h new file mode 100644 index 00000000..c70add6a --- /dev/null +++ b/tutorials/rp/usb/mongoose_config.h @@ -0,0 +1,22 @@ +#pragma once +#define MG_ARCH MG_ARCH_PICOSDK +#define MG_TLS MG_TLS_BUILTIN +#define MG_ENABLE_TCPIP 1 +#define MG_ENABLE_DRIVER_USB_RP 1 // RP2040 / RP2350 USB controller +#define MG_ENABLE_USB_ETHERNET 1 // USB NCM Ethernet interface +#define MG_ENABLE_USB_SERIAL 1 // USB serial log console + +// Static device address; the driver serves DHCP to the USB host. Remove +// these to get an address over DHCP instead, e.g. from Internet Sharing +#define MG_TCPIP_IP MG_IPV4(192, 168, 7, 1) +#define MG_TCPIP_MASK MG_IPV4(255, 255, 255, 0) + +#define MG_SET_MAC_ADDRESS(mac) \ + do { \ + mac[0] = 2; \ + mac[1] = 3; \ + mac[2] = 4; \ + mac[3] = 5; \ + mac[4] = 6; \ + mac[5] = 7; \ + } while (0)