Fix up all the newly imported Teensy code

Change-Id: Id051083a16336617add1d5f16fc7b7d78a30a5fe
diff --git a/motors/usb/BUILD b/motors/usb/BUILD
new file mode 100644
index 0000000..801f926
--- /dev/null
+++ b/motors/usb/BUILD
@@ -0,0 +1,24 @@
+cc_library(
+  name = 'usb',
+  visibility = ['//visibility:public'],
+  hdrs = [
+    'usb_desc.h',
+    'usb_serial.h',
+    'usb_dev.h',
+  ],
+  srcs = [
+    'usb_mem.h',
+    'usb_names.h',
+
+    'usb_desc.c',
+    'usb_serial.c',
+    'usb_dev.c',
+    'usb_mem.c',
+  ],
+  defines = [
+    'USB_SERIAL=1',
+  ],
+  deps = [
+    '//motors/core',
+  ],
+)
diff --git a/motors/usb/usb_desc.c b/motors/usb/usb_desc.c
index efb50a8..62ed242 100644
--- a/motors/usb/usb_desc.c
+++ b/motors/usb/usb_desc.c
@@ -31,11 +31,11 @@
 #if F_CPU >= 20000000
 
 #define USB_DESC_LIST_DEFINE
-#include "usb_desc.h"
+#include "motors/usb/usb_desc.h"
 #ifdef NUM_ENDPOINTS
-#include "usb_names.h"
-#include "kinetis.h"
-#include "avr_functions.h"
+#include "motors/usb/usb_names.h"
+#include "motors/core/kinetis.h"
+#include "motors/core/nonstd.h"
 
 // USB Descriptors are binary data which the USB host reads to
 // automatically detect a USB device's capabilities.  The format
@@ -470,7 +470,14 @@
 #define CDC_DATA_INTERFACE_DESC_SIZE	0
 #endif
 
-#define MIDI_INTERFACE_DESC_POS		CDC_DATA_INTERFACE_DESC_POS+CDC_DATA_INTERFACE_DESC_SIZE
+#define CDC2_DATA_INTERFACE_DESC_POS	CDC_DATA_INTERFACE_DESC_POS+CDC_DATA_INTERFACE_DESC_SIZE
+#ifdef  CDC2_DATA_INTERFACE
+#define CDC2_DATA_INTERFACE_DESC_SIZE	9+5+5+4+5+7+9+7+7
+#else
+#define CDC2_DATA_INTERFACE_DESC_SIZE	0
+#endif
+
+#define MIDI_INTERFACE_DESC_POS		CDC2_DATA_INTERFACE_DESC_POS+CDC2_DATA_INTERFACE_DESC_SIZE
 #ifdef  MIDI_INTERFACE
 #define MIDI_INTERFACE_DESC_SIZE	9+7+6+6+9+9+9+5+9+5
 #else
@@ -655,6 +662,72 @@
         0,                                      // bInterval
 #endif // CDC_DATA_INTERFACE
 
+#ifdef CDC2_DATA_INTERFACE
+        // interface descriptor, USB spec 9.6.5, page 267-269, Table 9-12
+        9,                                      // bLength
+        4,                                      // bDescriptorType
+        CDC2_STATUS_INTERFACE,			// bInterfaceNumber
+        0,                                      // bAlternateSetting
+        1,                                      // bNumEndpoints
+        0x02,                                   // bInterfaceClass
+        0x02,                                   // bInterfaceSubClass
+        0x01,                                   // bInterfaceProtocol
+        0,                                      // iInterface
+        // CDC Header Functional Descriptor, CDC Spec 5.2.3.1, Table 26
+        5,                                      // bFunctionLength
+        0x24,                                   // bDescriptorType
+        0x00,                                   // bDescriptorSubtype
+        0x10, 0x01,                             // bcdCDC
+        // Call Management Functional Descriptor, CDC Spec 5.2.3.2, Table 27
+        5,                                      // bFunctionLength
+        0x24,                                   // bDescriptorType
+        0x01,                                   // bDescriptorSubtype
+        0x01,                                   // bmCapabilities
+        1,                                      // bDataInterface
+        // Abstract Control Management Functional Descriptor, CDC Spec 5.2.3.3, Table 28
+        4,                                      // bFunctionLength
+        0x24,                                   // bDescriptorType
+        0x02,                                   // bDescriptorSubtype
+        0x06,                                   // bmCapabilities
+        // Union Functional Descriptor, CDC Spec 5.2.3.8, Table 33
+        5,                                      // bFunctionLength
+        0x24,                                   // bDescriptorType
+        0x06,                                   // bDescriptorSubtype
+        CDC2_STATUS_INTERFACE,                   // bMasterInterface
+        CDC2_DATA_INTERFACE,                     // bSlaveInterface0
+        // endpoint descriptor, USB spec 9.6.6, page 269-271, Table 9-13
+        7,                                      // bLength
+        5,                                      // bDescriptorType
+        CDC2_ACM_ENDPOINT | 0x80,                // bEndpointAddress
+        0x03,                                   // bmAttributes (0x03=intr)
+        CDC_ACM_SIZE, 0,                        // wMaxPacketSize
+        64,                                     // bInterval
+        // interface descriptor, USB spec 9.6.5, page 267-269, Table 9-12
+        9,                                      // bLength
+        4,                                      // bDescriptorType
+        CDC2_DATA_INTERFACE,                     // bInterfaceNumber
+        0,                                      // bAlternateSetting
+        2,                                      // bNumEndpoints
+        0x0A,                                   // bInterfaceClass
+        0x00,                                   // bInterfaceSubClass
+        0x00,                                   // bInterfaceProtocol
+        0,                                      // iInterface
+        // endpoint descriptor, USB spec 9.6.6, page 269-271, Table 9-13
+        7,                                      // bLength
+        5,                                      // bDescriptorType
+        CDC2_RX_ENDPOINT,                        // bEndpointAddress
+        0x02,                                   // bmAttributes (0x02=bulk)
+        CDC_RX_SIZE, 0,                         // wMaxPacketSize
+        0,                                      // bInterval
+        // endpoint descriptor, USB spec 9.6.6, page 269-271, Table 9-13
+        7,                                      // bLength
+        5,                                      // bDescriptorType
+        CDC2_TX_ENDPOINT | 0x80,                 // bEndpointAddress
+        0x02,                                   // bmAttributes (0x02=bulk)
+        CDC_TX_SIZE, 0,                         // wMaxPacketSize
+        0,                                      // bInterval
+#endif // CDC_DATA_INTERFACE
+
 #ifdef MIDI_INTERFACE
         // Standard MS Interface Descriptor,
         9,                                      // bLength
@@ -1310,14 +1383,14 @@
 	FTFL_FCCOB1 = 15;
 	FTFL_FSTAT = FTFL_FSTAT_CCIF;
 	while (!(FTFL_FSTAT & FTFL_FSTAT_CCIF)) ; // wait
-	num = *(uint32_t *)&FTFL_FCCOB7;
+	num = *(volatile uint32_t *)&FTFL_FCCOB7;
 #elif defined(HAS_KINETIS_FLASH_FTFE)
 	kinetis_hsrun_disable();
 	FTFL_FSTAT = FTFL_FSTAT_RDCOLERR | FTFL_FSTAT_ACCERR | FTFL_FSTAT_FPVIOL;
-	*(uint32_t *)&FTFL_FCCOB3 = 0x41070000;
+	*(volatile uint32_t *)&FTFL_FCCOB3 = 0x41070000;
 	FTFL_FSTAT = FTFL_FSTAT_CCIF;
 	while (!(FTFL_FSTAT & FTFL_FSTAT_CCIF)) ; // wait
-	num = *(uint32_t *)&FTFL_FCCOBB;
+	num = *(volatile uint32_t *)&FTFL_FCCOBB;
 	kinetis_hsrun_enable();
 #endif
 	__enable_irq();
@@ -1483,6 +1556,10 @@
 #endif
 };
 
+void usb_descriptor_set_product_id(uint16_t product_id) {
+  device_descriptor[10] = LSB(product_id);
+  device_descriptor[11] = MSB(product_id);
+}
 
 #endif // NUM_ENDPOINTS
 #endif // F_CPU >= 20 MHz
diff --git a/motors/usb/usb_desc.h b/motors/usb/usb_desc.h
index b59640d..e8459ce 100644
--- a/motors/usb/usb_desc.h
+++ b/motors/usb/usb_desc.h
@@ -39,6 +39,11 @@
 #include <stdint.h>
 #include <stddef.h>
 
+#ifdef __cplusplus
+extern "C"
+{
+#endif
+
 #define ENDPOINT_UNUSED			0x00
 #define ENDPOINT_TRANSIMIT_ONLY		0x15
 #define ENDPOINT_RECEIVE_ONLY		0x19
@@ -120,23 +125,31 @@
   #define DEVICE_CLASS		2	// 2 = Communication Class
   #define MANUFACTURER_NAME	{'T','e','e','n','s','y','d','u','i','n','o'}
   #define MANUFACTURER_NAME_LEN	11
-  #define PRODUCT_NAME		{'U','S','B',' ','S','e','r','i','a','l'}
-  #define PRODUCT_NAME_LEN	10
+  #define PRODUCT_NAME		{'U','S','B',' ','S','e','r','i','a','l',' ','x','2'}
+  #define PRODUCT_NAME_LEN	13
   #define EP0_SIZE		64
-  #define NUM_ENDPOINTS		4
-  #define NUM_USB_BUFFERS	12
-  #define NUM_INTERFACE		2
+  #define NUM_ENDPOINTS		7
+  #define NUM_USB_BUFFERS	24
+  #define NUM_INTERFACE		4
   #define CDC_STATUS_INTERFACE	0
   #define CDC_DATA_INTERFACE	1
+  #define CDC2_STATUS_INTERFACE	2
+  #define CDC2_DATA_INTERFACE	3
   #define CDC_ACM_ENDPOINT	2
   #define CDC_RX_ENDPOINT       3
   #define CDC_TX_ENDPOINT       4
+  #define CDC2_ACM_ENDPOINT	5
+  #define CDC2_RX_ENDPOINT       6
+  #define CDC2_TX_ENDPOINT       7
   #define CDC_ACM_SIZE          16
   #define CDC_RX_SIZE           64
   #define CDC_TX_SIZE           64
   #define ENDPOINT2_CONFIG	ENDPOINT_TRANSIMIT_ONLY
   #define ENDPOINT3_CONFIG	ENDPOINT_RECEIVE_ONLY
   #define ENDPOINT4_CONFIG	ENDPOINT_TRANSIMIT_ONLY
+  #define ENDPOINT5_CONFIG	ENDPOINT_TRANSIMIT_ONLY
+  #define ENDPOINT6_CONFIG	ENDPOINT_RECEIVE_ONLY
+  #define ENDPOINT7_CONFIG	ENDPOINT_TRANSIMIT_ONLY
 
 #elif defined(USB_KEYBOARDONLY)
   #define VENDOR_ID		0x16C0
@@ -708,4 +721,10 @@
 #endif // NUM_ENDPOINTS
 #endif // USB_DESC_LIST_DEFINE
 
+void usb_descriptor_set_product_id(uint16_t product_id);
+
+#ifdef __cplusplus
+}
+#endif
+
 #endif
diff --git a/motors/usb/usb_dev.c b/motors/usb/usb_dev.c
index d57ca5d..8dc8e1f 100644
--- a/motors/usb/usb_dev.c
+++ b/motors/usb/usb_dev.c
@@ -37,19 +37,30 @@
  *   https://github.com/payne92/bare-metal-arm
  */
 
-#include "usb_dev.h"
+#include "motors/usb/usb_dev.h"
 #if F_CPU >= 20000000 && defined(NUM_ENDPOINTS)
 
-#include "kinetis.h"
-//#include "HardwareSerial.h"
-#include "usb_mem.h"
+#include "motors/core/kinetis.h"
+#include "motors/usb/usb_mem.h"
 #include <string.h> // for memset
 
+#ifdef CDC_DATA_INTERFACE
+extern uint32_t usb_cdc_line_coding[2];
+extern volatile uint32_t usb_cdc_line_rtsdtr_millis;
+extern volatile uint32_t systick_millis_count;
+extern volatile uint8_t usb_cdc_line_rtsdtr;
+extern volatile uint8_t *usb_cdc_transmit_flush_timer;
+extern void usb_serial_flush_callback(int);
+#endif
+#ifdef CDC2_DATA_INTERFACE
+extern volatile uint8_t *usb_cdc2_transmit_flush_timer;
+#endif
+
 // buffer descriptor table
 
 typedef struct {
 	uint32_t desc;
-	void * addr;
+	const void * addr;
 } bdt_t;
 
 __attribute__ ((section(".usbdescriptortable"), used))
@@ -146,15 +157,7 @@
 
 static void endpoint0_transmit(const void *data, uint32_t len)
 {
-#if 0
-	serial_print("tx0:");
-	serial_phex32((uint32_t)data);
-	serial_print(",");
-	serial_phex16(len);
-	serial_print(ep0_tx_bdt_bank ? ", odd" : ", even");
-	serial_print(ep0_tx_data_toggle ? ", d1\n" : ", d0\n");
-#endif
-	table[index(0, TX, ep0_tx_bdt_bank)].addr = (void *)data;
+	table[index(0, TX, ep0_tx_bdt_bank)].addr = (const void *)data;
 	table[index(0, TX, ep0_tx_bdt_bank)].desc = BDT_DESC(len, ep0_tx_data_toggle);
 	ep0_tx_data_toggle ^= 1;
 	ep0_tx_bdt_bank ^= 1;
@@ -177,14 +180,13 @@
 	  case 0x0500: // SET_ADDRESS
 		break;
 	  case 0x0900: // SET_CONFIGURATION
-		//serial_print("configure\n");
 		usb_configuration = setup.wValue;
 		reg = &USB0_ENDPT1;
 		cfg = usb_endpoint_config_table;
 		// clear all BDT entries, free any allocated memory...
 		for (i=4; i < (NUM_ENDPOINTS+1)*4; i++) {
 			if (table[i].desc & BDT_OWN) {
-				usb_free((usb_packet_t *)((uint8_t *)(table[i].addr) - 8));
+				usb_free((const usb_packet_t *)((const uint8_t *)(table[i].addr) - 8));
 			}
 		}
 		// free all queued packets
@@ -282,7 +284,9 @@
 		}
 		reply_buffer[0] = 0;
 		reply_buffer[1] = 0;
-		if (*(uint8_t *)(&USB0_ENDPT0 + i * 4) & 0x02) reply_buffer[0] = 1;
+		if (*(volatile uint8_t *)(&USB0_ENDPT0 + i * 4) & 0x02) {
+      reply_buffer[0] = 1;
+    }
 		data = reply_buffer;
 		datalen = 2;
 		break;
@@ -293,7 +297,7 @@
 			endpoint0_stall();
 			return;
 		}
-		(*(uint8_t *)(&USB0_ENDPT0 + i * 4)) &= ~0x02;
+		(*(volatile uint8_t *)(&USB0_ENDPT0 + i * 4)) &= ~0x02;
 		// TODO: do we need to clear the data toggle here?
 		break;
 	  case 0x0302: // SET_FEATURE (endpoint)
@@ -303,18 +307,13 @@
 			endpoint0_stall();
 			return;
 		}
-		(*(uint8_t *)(&USB0_ENDPT0 + i * 4)) |= 0x02;
+		(*(volatile uint8_t *)(&USB0_ENDPT0 + i * 4)) |= 0x02;
 		// TODO: do we need to clear the data toggle here?
 		break;
 	  case 0x0680: // GET_DESCRIPTOR
 	  case 0x0681:
-		//serial_print("desc:");
-		//serial_phex16(setup.wValue);
-		//serial_print("\n");
 		for (list = usb_descriptor_list; 1; list++) {
 			if (list->addr == NULL) break;
-			//if (setup.wValue == list->wValue &&
-			//(setup.wIndex == list->wIndex) || ((setup.wValue >> 8) == 3)) {
 			if (setup.wValue == list->wValue && setup.wIndex == list->wIndex) {
 				data = list->addr;
 				if ((setup.wValue >> 8) == 3) {
@@ -325,36 +324,21 @@
 				} else {
 					datalen = list->length;
 				}
-#if 0
-				serial_print("Desc found, ");
-				serial_phex32((uint32_t)data);
-				serial_print(",");
-				serial_phex16(datalen);
-				serial_print(",");
-				serial_phex(data[0]);
-				serial_phex(data[1]);
-				serial_phex(data[2]);
-				serial_phex(data[3]);
-				serial_phex(data[4]);
-				serial_phex(data[5]);
-				serial_print("\n");
-#endif
 				goto send;
 			}
 		}
-		//serial_print("desc: not found\n");
 		endpoint0_stall();
 		return;
 #if defined(CDC_STATUS_INTERFACE)
 	  case 0x2221: // CDC_SET_CONTROL_LINE_STATE
+		// TODO(Brian): wIndex is the interface number this is directed at. Pay
+		//              attention to that.
 		usb_cdc_line_rtsdtr_millis = systick_millis_count;
 		usb_cdc_line_rtsdtr = setup.wValue;
-		//serial_print("set control line state\n");
 		break;
 	  case 0x2321: // CDC_SEND_BREAK
 		break;
 	  case 0x2021: // CDC_SET_LINE_CODING
-		//serial_print("set coding, waiting...\n");
 		return;
 #endif
 
@@ -381,7 +365,6 @@
 // TODO: this does not work... why?
 #if defined(SEREMU_INTERFACE) || defined(KEYBOARD_INTERFACE)
 	  case 0x0921: // HID SET_REPORT
-		//serial_print(":)\n");
 		return;
 	  case 0x0A21: // HID SET_IDLE
 		break;
@@ -472,11 +455,6 @@
 		return;
 	}
 	send:
-	//serial_print("setup send ");
-	//serial_phex32(data);
-	//serial_print(",");
-	//serial_phex16(datalen);
-	//serial_print("\n");
 
 	if (datalen > setup.wLength) datalen = setup.wLength;
 	size = datalen;
@@ -520,60 +498,31 @@
 {
 	bdt_t *b;
 	uint32_t pid, size;
-	uint8_t *buf;
+	const uint8_t *buf;
 	const uint8_t *data;
 
 	b = stat2bufferdescriptor(stat);
 	pid = BDT_PID(b->desc);
-	//count = b->desc >> 16;
 	buf = b->addr;
-	//serial_print("pid:");
-	//serial_phex(pid);
-	//serial_print(", count:");
-	//serial_phex(count);
-	//serial_print("\n");
 
 	switch (pid) {
 	case 0x0D: // Setup received from host
-		//serial_print("PID=Setup\n");
-		//if (count != 8) ; // panic?
 		// grab the 8 byte setup info
-		setup.word1 = *(uint32_t *)(buf);
-		setup.word2 = *(uint32_t *)(buf + 4);
+		setup.word1 = *(const uint32_t *)(buf);
+		setup.word2 = *(const uint32_t *)(buf + 4);
 
 		// give the buffer back
 		b->desc = BDT_DESC(EP0_SIZE, DATA1);
-		//table[index(0, RX, EVEN)].desc = BDT_DESC(EP0_SIZE, 1);
-		//table[index(0, RX, ODD)].desc = BDT_DESC(EP0_SIZE, 1);
 
 		// clear any leftover pending IN transactions
 		ep0_tx_ptr = NULL;
 		if (ep0_tx_data_toggle) {
 		}
-		//if (table[index(0, TX, EVEN)].desc & 0x80) {
-			//serial_print("leftover tx even\n");
-		//}
-		//if (table[index(0, TX, ODD)].desc & 0x80) {
-			//serial_print("leftover tx odd\n");
-		//}
 		table[index(0, TX, EVEN)].desc = 0;
 		table[index(0, TX, ODD)].desc = 0;
 		// first IN after Setup is always DATA1
 		ep0_tx_data_toggle = 1;
 
-#if 0
-		serial_print("bmRequestType:");
-		serial_phex(setup.bmRequestType);
-		serial_print(", bRequest:");
-		serial_phex(setup.bRequest);
-		serial_print(", wValue:");
-		serial_phex16(setup.wValue);
-		serial_print(", wIndex:");
-		serial_phex16(setup.wIndex);
-		serial_print(", len:");
-		serial_phex16(setup.wLength);
-		serial_print("\n");
-#endif
 		// actually "do" the setup request
 		usb_setup();
 		// unfreeze the USB, now that we're ready
@@ -581,18 +530,15 @@
 		break;
 	case 0x01:  // OUT transaction received from host
 	case 0x02:
-		//serial_print("PID=OUT\n");
 #ifdef CDC_STATUS_INTERFACE
+		// TODO(Brian): wIndex is the interface number this is directed at. Pay
+		//              attention to that.
 		if (setup.wRequestAndType == 0x2021 /*CDC_SET_LINE_CODING*/) {
 			int i;
 			uint8_t *dst = (uint8_t *)usb_cdc_line_coding;
-			//serial_print("set line coding ");
 			for (i=0; i<7; i++) {
-				//serial_phex(*buf);
 				*dst++ = *buf++;
 			}
-			//serial_phex32(usb_cdc_line_coding[0]);
-			//serial_print("\n");
 			if (usb_cdc_line_coding[0] == 134) usb_reboot_timer = 15;
 			endpoint0_transmit(NULL, 0);
 		}
@@ -620,9 +566,6 @@
 		break;
 
 	case 0x09: // IN transaction completed to host
-		//serial_print("PID=IN:");
-		//serial_phex(stat);
-		//serial_print("\n");
 
 		// send remaining data, if any...
 		data = ep0_tx_ptr;
@@ -637,17 +580,10 @@
 
 		if (setup.bRequest == 5 && setup.bmRequestType == 0) {
 			setup.bRequest = 0;
-			//serial_print("set address: ");
-			//serial_phex16(setup.wValue);
-			//serial_print("\n");
 			USB0_ADDR = setup.wValue;
 		}
 
 		break;
-	//default:
-		//serial_print("PID=unknown:");
-		//serial_phex(pid);
-		//serial_print("\n");
 	}
 	USB0_CTL = USB_CTL_USBENSOFEN; // clear TXSUSPENDTOKENBUSY bit
 }
@@ -669,11 +605,6 @@
 		usb_rx_byte_count_data[endpoint] -= ret->len;
 	}
 	__enable_irq();
-	//serial_print("rx, epidx=");
-	//serial_phex(endpoint);
-	//serial_print(", packet=");
-	//serial_phex32(ret);
-	//serial_print("\n");
 	return ret;
 }
 
@@ -689,17 +620,6 @@
 	return count;
 }
 
-// TODO: make this an inline function...
-/*
-uint32_t usb_rx_byte_count(uint32_t endpoint)
-{
-	endpoint--;
-	if (endpoint >= NUM_ENDPOINTS) return 0;
-	return usb_rx_byte_count_data[endpoint];
-	//return usb_queue_byte_count(rx_first[endpoint]);
-}
-*/
-
 uint32_t usb_tx_byte_count(uint32_t endpoint)
 {
 	endpoint--;
@@ -729,13 +649,12 @@
 // without this prioritization.  The packet buffer (input) is assigned to the
 // first endpoint needing memory.
 //
-void usb_rx_memory(usb_packet_t *packet)
+void usb_rx_memory(const usb_packet_t *packet)
 {
 	unsigned int i;
 	const uint8_t *cfg;
 
 	cfg = usb_endpoint_config_table;
-	//serial_print("rx_mem:");
 	__disable_irq();
 	for (i=1; i <= NUM_ENDPOINTS; i++) {
 #ifdef AUDIO_INTERFACE
@@ -747,8 +666,6 @@
 				table[index(i, RX, EVEN)].desc = BDT_DESC(64, 0);
 				usb_rx_memory_needed--;
 				__enable_irq();
-				//serial_phex(i);
-				//serial_print(",even\n");
 				return;
 			}
 			if (table[index(i, RX, ODD)].desc == 0) {
@@ -756,8 +673,6 @@
 				table[index(i, RX, ODD)].desc = BDT_DESC(64, 1);
 				usb_rx_memory_needed--;
 				__enable_irq();
-				//serial_phex(i);
-				//serial_print(",odd\n");
 				return;
 			}
 		}
@@ -782,9 +697,6 @@
 	endpoint--;
 	if (endpoint >= NUM_ENDPOINTS) return;
 	__disable_irq();
-	//serial_print("txstate=");
-	//serial_phex(tx_state[endpoint]);
-	//serial_print("\n");
 	switch (tx_state[endpoint]) {
 	  case TX_STATE_BOTH_FREE_EVEN_FIRST:
 		next = TX_STATE_ODD_FREE;
@@ -852,10 +764,6 @@
 {
 	uint8_t status, stat, t;
 
-	//serial_print("isr");
-	//status = USB0_ISTAT;
-	//serial_phex(status);
-	//serial_print("\n");
 	restart:
 	status = USB0_ISTAT;
 
@@ -867,10 +775,17 @@
 				if (!t) _reboot_Teensyduino_();
 			}
 #ifdef CDC_DATA_INTERFACE
-			t = usb_cdc_transmit_flush_timer;
+			t = *usb_cdc_transmit_flush_timer;
 			if (t) {
-				usb_cdc_transmit_flush_timer = --t;
-				if (t == 0) usb_serial_flush_callback();
+				*usb_cdc_transmit_flush_timer = --t;
+				if (t == 0) usb_serial_flush_callback(0);
+			}
+#endif
+#ifdef CDC2_DATA_INTERFACE
+			t = *usb_cdc2_transmit_flush_timer;
+			if (t) {
+				*usb_cdc2_transmit_flush_timer = --t;
+				if (t == 0) usb_serial_flush_callback(1);
 			}
 #endif
 #ifdef SEREMU_INTERFACE
@@ -896,26 +811,15 @@
 	if ((status & USB_ISTAT_TOKDNE /* 08 */ )) {
 		uint8_t endpoint;
 		stat = USB0_STAT;
-		//serial_print("token: ep=");
-		//serial_phex(stat >> 4);
-		//serial_print(stat & 0x08 ? ",tx" : ",rx");
-		//serial_print(stat & 0x04 ? ",odd\n" : ",even\n");
 		endpoint = stat >> 4;
 		if (endpoint == 0) {
 			usb_control(stat);
 		} else {
 			bdt_t *b = stat2bufferdescriptor(stat);
+#pragma GCC diagnostic push
+#pragma GCC diagnostic ignored "-Wcast-qual"
 			usb_packet_t *packet = (usb_packet_t *)((uint8_t *)(b->addr) - 8);
-#if 0
-			serial_print("ep:");
-			serial_phex(endpoint);
-			serial_print(", pid:");
-			serial_phex(BDT_PID(b->desc));
-			serial_print(((uint32_t)b & 8) ? ", odd" : ", even");
-			serial_print(", count:");
-			serial_phex(b->desc >> 16);
-			serial_print("\n");
-#endif
+#pragma GCC diagnostic pop
 			endpoint--;	// endpoint is index to zero-based arrays
 
 #ifdef AUDIO_INTERFACE
@@ -943,7 +847,6 @@
 				usb_free(packet);
 				packet = tx_first[endpoint];
 				if (packet) {
-					//serial_print("tx packet\n");
 					tx_first[endpoint] = packet->next;
 					b->addr = packet->buf;
 					switch (tx_state[endpoint]) {
@@ -965,7 +868,6 @@
 					b->desc = BDT_DESC(packet->len,
 						((uint32_t)b & 8) ? DATA1 : DATA0);
 				} else {
-					//serial_print("tx no packet\n");
 					switch (tx_state[endpoint]) {
 					  case TX_STATE_BOTH_FREE_EVEN_FIRST:
 					  case TX_STATE_BOTH_FREE_ODD_FIRST:
@@ -988,18 +890,8 @@
 					packet->index = 0;
 					packet->next = NULL;
 					if (rx_first[endpoint] == NULL) {
-						//serial_print("rx 1st, epidx=");
-						//serial_phex(endpoint);
-						//serial_print(", packet=");
-						//serial_phex32((uint32_t)packet);
-						//serial_print("\n");
 						rx_first[endpoint] = packet;
 					} else {
-						//serial_print("rx Nth, epidx=");
-						//serial_phex(endpoint);
-						//serial_print(", packet=");
-						//serial_phex32((uint32_t)packet);
-						//serial_print("\n");
 						rx_last[endpoint]->next = packet;
 					}
 					rx_last[endpoint] = packet;
@@ -1014,8 +906,6 @@
 						b->desc = BDT_DESC(64,
 							((uint32_t)b & 8) ? DATA1 : DATA0);
 					} else {
-						//serial_print("starving ");
-						//serial_phex(endpoint + 1);
 						b->desc = 0;
 						usb_rx_memory_needed++;
 					}
@@ -1032,8 +922,6 @@
 
 
 	if (status & USB_ISTAT_USBRST /* 01 */ ) {
-		//serial_print("reset\n");
-
 		// initialize BDT toggle bits
 		USB0_CTL = USB_CTL_ODDRST;
 		ep0_tx_bdt_bank = 0;
@@ -1072,21 +960,16 @@
 
 
 	if ((status & USB_ISTAT_STALL /* 80 */ )) {
-		//serial_print("stall:\n");
 		USB0_ENDPT0 = USB_ENDPT_EPRXEN | USB_ENDPT_EPTXEN | USB_ENDPT_EPHSHK;
 		USB0_ISTAT = USB_ISTAT_STALL;
 	}
 	if ((status & USB_ISTAT_ERROR /* 02 */ )) {
 		uint8_t err = USB0_ERRSTAT;
 		USB0_ERRSTAT = err;
-		//serial_print("err:");
-		//serial_phex(err);
-		//serial_print("\n");
 		USB0_ISTAT = USB_ISTAT_ERROR;
 	}
 
 	if ((status & USB_ISTAT_SLEEP /* 10 */ )) {
-		//serial_print("sleep\n");
 		USB0_ISTAT = USB_ISTAT_SLEEP;
 	}
 
@@ -1098,9 +981,6 @@
 {
 	int i;
 
-	//serial_begin(BAUD2DIV(115200));
-	//serial_print("usb_init\n");
-
 	usb_init_serialnumber();
 
 	for (i=0; i <= NUM_ENDPOINTS*4; i++) {
@@ -1147,7 +1027,7 @@
 	USB0_INTEN = USB_INTEN_USBRSTEN;
 
 	// enable interrupt in NVIC...
-	NVIC_SET_PRIORITY(IRQ_USBOTG, 112);
+	//NVIC_SET_PRIORITY(IRQ_USBOTG, 112);
 	NVIC_ENABLE_IRQ(IRQ_USBOTG);
 
 	// enable d+ pullup
diff --git a/motors/usb/usb_dev.h b/motors/usb/usb_dev.h
index 1233d7f..c2e9d18 100644
--- a/motors/usb/usb_dev.h
+++ b/motors/usb/usb_dev.h
@@ -32,16 +32,14 @@
 #define _usb_dev_h_
 
 #define USB_DESC_LIST_DEFINE
-#include "usb_desc.h"
-
-#if F_CPU >= 20000000 && !defined(USB_DISABLED)
+#include "motors/usb/usb_desc.h"
 
 // This header is NOT meant to be included when compiling
 // user sketches in Arduino.  The low-level functions
 // provided by usb_dev.c are meant to be called only by
 // code which provides higher-level interfaces to the user.
 
-#include "usb_mem.h"
+#include "motors/usb/usb_mem.h"
 
 #ifdef __cplusplus
 extern "C" {
@@ -67,15 +65,6 @@
         return usb_rx_byte_count_data[endpoint];
 }
 
-#ifdef CDC_DATA_INTERFACE
-extern uint32_t usb_cdc_line_coding[2];
-extern volatile uint32_t usb_cdc_line_rtsdtr_millis;
-extern volatile uint32_t systick_millis_count;
-extern volatile uint8_t usb_cdc_line_rtsdtr;
-extern volatile uint8_t usb_cdc_transmit_flush_timer;
-extern void usb_serial_flush_callback(void);
-#endif
-
 #ifdef SEREMU_INTERFACE
 extern volatile uint8_t usb_seremu_transmit_flush_timer;
 extern void usb_seremu_flush_callback(void);
@@ -114,24 +103,8 @@
 extern void usb_touchscreen_update_callback(void);
 #endif
 
-
 #ifdef __cplusplus
 }
 #endif
 
-#else // F_CPU < 20000000
-
-#ifdef __cplusplus
-extern "C" {
-#endif
-
-void usb_init(void);
-
-#ifdef __cplusplus
-}
-#endif
-
-
-#endif // F_CPU
-
 #endif
diff --git a/motors/usb/usb_mem.c b/motors/usb/usb_mem.c
index 41b4596..e21e5a9 100644
--- a/motors/usb/usb_mem.c
+++ b/motors/usb/usb_mem.c
@@ -28,12 +28,12 @@
  * SOFTWARE.
  */
 
-#include "usb_dev.h"
+#include "motors/usb/usb_dev.h"
 #if F_CPU >= 20000000 && defined(NUM_ENDPOINTS)
 
-#include "kinetis.h"
+#include "motors/core/kinetis.h"
 //#include "HardwareSerial.h"
-#include "usb_mem.h"
+#include "motors/usb/usb_mem.h"
 
 __attribute__ ((section(".usbbuffers"), used))
 unsigned char usb_buffer_memory[NUM_USB_BUFFERS * sizeof(usb_packet_t)];
@@ -57,16 +57,11 @@
 		__enable_irq();
 		return NULL;
 	}
-	//serial_print("malloc:");
-	//serial_phex(n);
-	//serial_print("\n");
 
 	usb_buffer_available = avail & ~(0x80000000 >> n);
 	__enable_irq();
 	p = usb_buffer_memory + (n * sizeof(usb_packet_t));
-	//serial_print("malloc:");
-	//serial_phex32((int)p);
-	//serial_print("\n");
+
 	*(uint32_t *)p = 0;
 	*(uint32_t *)(p + 4) = 0;
 	return (usb_packet_t *)p;
@@ -74,24 +69,18 @@
 
 // for the receive endpoints to request memory
 extern uint8_t usb_rx_memory_needed;
-extern void usb_rx_memory(usb_packet_t *packet);
+extern void usb_rx_memory(const usb_packet_t *packet);
 
-void usb_free(usb_packet_t *p)
+void usb_free(const usb_packet_t *p)
 {
 	unsigned int n, mask;
 
-	//serial_print("free:");
-	n = ((uint8_t *)p - usb_buffer_memory) / sizeof(usb_packet_t);
+	n = ((const uint8_t *)p - usb_buffer_memory) / sizeof(usb_packet_t);
 	if (n >= NUM_USB_BUFFERS) return;
-	//serial_phex(n);
-	//serial_print("\n");
 
 	// if any endpoints are starving for memory to receive
 	// packets, give this memory to them immediately!
 	if (usb_rx_memory_needed && usb_configuration) {
-		//serial_print("give to rx:");
-		//serial_phex32((int)p);
-		//serial_print("\n");
 		usb_rx_memory(p);
 		return;
 	}
@@ -100,10 +89,6 @@
 	__disable_irq();
 	usb_buffer_available |= mask;
 	__enable_irq();
-
-	//serial_print("free:");
-	//serial_phex32((int)p);
-	//serial_print("\n");
 }
 
 #endif // F_CPU >= 20 MHz && defined(NUM_ENDPOINTS)
diff --git a/motors/usb/usb_mem.h b/motors/usb/usb_mem.h
index 8064488..b6014b5 100644
--- a/motors/usb/usb_mem.h
+++ b/motors/usb/usb_mem.h
@@ -45,7 +45,7 @@
 #endif
 
 usb_packet_t * usb_malloc(void);
-void usb_free(usb_packet_t *p);
+void usb_free(const usb_packet_t *p);
 
 #ifdef __cplusplus
 }
diff --git a/motors/usb/usb_serial.c b/motors/usb/usb_serial.c
index a312176..e7e6115 100644
--- a/motors/usb/usb_serial.c
+++ b/motors/usb/usb_serial.c
@@ -28,114 +28,124 @@
  * SOFTWARE.
  */
 
-#include "usb_dev.h"
-#include "usb_serial.h"
-#include "core_pins.h" // for yield()
-//#include "HardwareSerial.h"
-#include <string.h> // for memcpy()
+#include "motors/usb/usb_dev.h"
+#include "motors/usb/usb_serial.h"
+#include <string.h>
 
-// defined by usb_dev.h -> usb_desc.h
-#if defined(CDC_STATUS_INTERFACE) && defined(CDC_DATA_INTERFACE)
-#if F_CPU >= 20000000
-
+// These are shared between the two serial ports because they're ignored
+// anyways.
 uint32_t usb_cdc_line_coding[2];
 volatile uint32_t usb_cdc_line_rtsdtr_millis;
 volatile uint8_t usb_cdc_line_rtsdtr=0;
-volatile uint8_t usb_cdc_transmit_flush_timer=0;
 
-static usb_packet_t *rx_packet=NULL;
-static usb_packet_t *tx_packet=NULL;
-static volatile uint8_t tx_noautoflush=0;
+typedef struct {
+	usb_packet_t *rx_packet;
+	usb_packet_t *tx_packet;
+
+	uint32_t rx_endpoint;
+	uint32_t tx_endpoint;
+
+	volatile uint8_t tx_noautoflush;
+	volatile uint8_t transmit_flush_timer;
+} State;
+State states[2];
+
+volatile uint8_t *usb_cdc_transmit_flush_timer =
+    &states[0].transmit_flush_timer;
+volatile uint8_t *usb_cdc2_transmit_flush_timer =
+    &states[1].transmit_flush_timer;
 
 #define TRANSMIT_FLUSH_TIMEOUT	5   /* in milliseconds */
 
+void usb_serial_init(void) {
+	states[0].rx_endpoint = CDC_RX_ENDPOINT;
+	states[0].tx_endpoint = CDC_TX_ENDPOINT;
+	states[1].rx_endpoint = CDC2_RX_ENDPOINT;
+	states[1].tx_endpoint = CDC2_TX_ENDPOINT;
+}
+
 // get the next character, or -1 if nothing received
-int usb_serial_getchar(void)
+int usb_serial_getchar(int port)
 {
+	State *const state = &states[port];
 	unsigned int i;
 	int c;
 
-	if (!rx_packet) {
+	if (!state->rx_packet) {
 		if (!usb_configuration) return -1;
-		rx_packet = usb_rx(CDC_RX_ENDPOINT);
-		if (!rx_packet) return -1;
+		state->rx_packet = usb_rx(state->rx_endpoint);
+		if (!state->rx_packet) return -1;
 	}
-	i = rx_packet->index;
-	c = rx_packet->buf[i++];
-	if (i >= rx_packet->len) {
-		usb_free(rx_packet);
-		rx_packet = NULL;
+	i = state->rx_packet->index;
+	c = state->rx_packet->buf[i++];
+	if (i >= state->rx_packet->len) {
+		usb_free(state->rx_packet);
+		state->rx_packet = NULL;
 	} else {
-		rx_packet->index = i;
+		state->rx_packet->index = i;
 	}
 	return c;
 }
 
 // peek at the next character, or -1 if nothing received
-int usb_serial_peekchar(void)
+int usb_serial_peekchar(int port)
 {
-	if (!rx_packet) {
+	State *const state = &states[port];
+	if (!state->rx_packet) {
 		if (!usb_configuration) return -1;
-		rx_packet = usb_rx(CDC_RX_ENDPOINT);
-		if (!rx_packet) return -1;
+		state->rx_packet = usb_rx(state->rx_endpoint);
+		if (!state->rx_packet) return -1;
 	}
-	if (!rx_packet) return -1;
-	return rx_packet->buf[rx_packet->index];
-}
-
-// number of bytes available in the receive buffer
-int usb_serial_available(void)
-{
-	int count;
-	count = usb_rx_byte_count(CDC_RX_ENDPOINT);
-	if (rx_packet) count += rx_packet->len - rx_packet->index;
-	return count;
+	if (!state->rx_packet) return -1;
+	return state->rx_packet->buf[state->rx_packet->index];
 }
 
 // read a block of bytes to a buffer
-int usb_serial_read(void *buffer, uint32_t size)
+int usb_serial_read(int port, void *buffer, uint32_t size)
 {
+	State *const state = &states[port];
 	uint8_t *p = (uint8_t *)buffer;
 	uint32_t qty, count=0;
 
 	while (size) {
 		if (!usb_configuration) break;
-		if (!rx_packet) {
+		if (!state->rx_packet) {
 			rx:
-			rx_packet = usb_rx(CDC_RX_ENDPOINT);
-			if (!rx_packet) break;
-			if (rx_packet->len == 0) {
-				usb_free(rx_packet);
+			state->rx_packet = usb_rx(state->rx_endpoint);
+			if (!state->rx_packet) break;
+			if (state->rx_packet->len == 0) {
+				usb_free(state->rx_packet);
 				goto rx;
 			}
 		}
-		qty = rx_packet->len - rx_packet->index;
+		qty = state->rx_packet->len - state->rx_packet->index;
 		if (qty > size) qty = size;
-		memcpy(p, rx_packet->buf + rx_packet->index, qty);
+		memcpy(p, state->rx_packet->buf + state->rx_packet->index, qty);
 		p += qty;
 		count += qty;
 		size -= qty;
-		rx_packet->index += qty;
-		if (rx_packet->index >= rx_packet->len) {
-			usb_free(rx_packet);
-			rx_packet = NULL;
+		state->rx_packet->index += qty;
+		if (state->rx_packet->index >= state->rx_packet->len) {
+			usb_free(state->rx_packet);
+			state->rx_packet = NULL;
 		}
 	}
 	return count;
 }
 
 // discard any buffered input
-void usb_serial_flush_input(void)
+void usb_serial_flush_input(int port)
 {
+	State *const state = &states[port];
 	usb_packet_t *rx;
 
 	if (!usb_configuration) return;
-	if (rx_packet) {
-		usb_free(rx_packet);
-		rx_packet = NULL;
+	if (state->rx_packet) {
+		usb_free(state->rx_packet);
+		state->rx_packet = NULL;
 	}
 	while (1) {
-		rx = usb_rx(CDC_RX_ENDPOINT);
+		rx = usb_rx(state->rx_endpoint);
 		if (!rx) break;
 		usb_free(rx);
 	}
@@ -173,133 +183,83 @@
   #define TX_TIMEOUT (TX_TIMEOUT_MSEC * 262)
 #endif
 
-// When we've suffered the transmit timeout, don't wait again until the computer
-// begins accepting data.  If no software is running to receive, we'll just discard
-// data as rapidly as Serial.print() can generate it, until there's something to
-// actually receive it.
-static uint8_t transmit_previous_timeout=0;
-
-
-// transmit a character.  0 returned on success, -1 on error
-int usb_serial_putchar(uint8_t c)
+int usb_serial_write(int port, const void *buffer, uint32_t size)
 {
-	return usb_serial_write(&c, 1);
-}
-
-
-int usb_serial_write(const void *buffer, uint32_t size)
-{
-	uint32_t ret = size;
+	State *const state = &states[port];
 	uint32_t len;
-	uint32_t wait_count;
 	const uint8_t *src = (const uint8_t *)buffer;
 	uint8_t *dest;
 
-	tx_noautoflush = 1;
+	state->tx_noautoflush = 1;
 	while (size > 0) {
-		if (!tx_packet) {
-			wait_count = 0;
+		if (!state->tx_packet) {
 			while (1) {
 				if (!usb_configuration) {
-					tx_noautoflush = 0;
+					state->tx_noautoflush = 0;
 					return -1;
 				}
-				if (usb_tx_packet_count(CDC_TX_ENDPOINT) < TX_PACKET_LIMIT) {
-					tx_noautoflush = 1;
-					tx_packet = usb_malloc();
-					if (tx_packet) break;
-					tx_noautoflush = 0;
+				if (usb_tx_packet_count(state->tx_endpoint) < TX_PACKET_LIMIT) {
+					state->tx_noautoflush = 1;
+					state->tx_packet = usb_malloc();
+					if (state->tx_packet) break;
+					state->tx_noautoflush = 0;
 				}
-				if (++wait_count > TX_TIMEOUT || transmit_previous_timeout) {
-					transmit_previous_timeout = 1;
-					return -1;
-				}
-				yield();
+				return -1;
 			}
 		}
-		transmit_previous_timeout = 0;
-		len = CDC_TX_SIZE - tx_packet->index;
+		len = CDC_TX_SIZE - state->tx_packet->index;
 		if (len > size) len = size;
-		dest = tx_packet->buf + tx_packet->index;
-		tx_packet->index += len;
+		dest = state->tx_packet->buf + state->tx_packet->index;
+		state->tx_packet->index += len;
 		size -= len;
 		while (len-- > 0) *dest++ = *src++;
-		if (tx_packet->index >= CDC_TX_SIZE) {
-			tx_packet->len = CDC_TX_SIZE;
-			usb_tx(CDC_TX_ENDPOINT, tx_packet);
-			tx_packet = NULL;
+		if (state->tx_packet->index >= CDC_TX_SIZE) {
+			state->tx_packet->len = CDC_TX_SIZE;
+			usb_tx(state->tx_endpoint, state->tx_packet);
+			state->tx_packet = NULL;
 		}
-		usb_cdc_transmit_flush_timer = TRANSMIT_FLUSH_TIMEOUT;
+		state->transmit_flush_timer = TRANSMIT_FLUSH_TIMEOUT;
 	}
-	tx_noautoflush = 0;
-	return ret;
+	state->tx_noautoflush = 0;
+	return size;
 }
 
-int usb_serial_write_buffer_free(void)
+void usb_serial_flush_output(int port)
 {
-	uint32_t len;
-
-	tx_noautoflush = 1;
-	if (!tx_packet) {
-		if (!usb_configuration ||
-		  usb_tx_packet_count(CDC_TX_ENDPOINT) >= TX_PACKET_LIMIT ||
-		  (tx_packet = usb_malloc()) == NULL) {
-			tx_noautoflush = 0;
-			return 0;
-		}
-	}
-	len = CDC_TX_SIZE - tx_packet->index;
-	// TODO: Perhaps we need "usb_cdc_transmit_flush_timer = TRANSMIT_FLUSH_TIMEOUT"
-	// added here, so the SOF interrupt can't take away the available buffer
-	// space we just promised the user could write without blocking?
-	// But does this come with other performance downsides?  Could it lead to
-	// buffer data never actually transmitting in some usage cases?  More
-	// investigation is needed.
-	// https://github.com/PaulStoffregen/cores/issues/10#issuecomment-61514955
-	tx_noautoflush = 0;
-	return len;
-}
-
-void usb_serial_flush_output(void)
-{
+	State *const state = &states[port];
 	if (!usb_configuration) return;
-	tx_noautoflush = 1;
-	if (tx_packet) {
-		usb_cdc_transmit_flush_timer = 0;
-		tx_packet->len = tx_packet->index;
-		usb_tx(CDC_TX_ENDPOINT, tx_packet);
-		tx_packet = NULL;
+	state->tx_noautoflush = 1;
+	if (state->tx_packet) {
+		state->transmit_flush_timer = 0;
+		state->tx_packet->len = state->tx_packet->index;
+		usb_tx(state->tx_endpoint, state->tx_packet);
+		state->tx_packet = NULL;
 	} else {
 		usb_packet_t *tx = usb_malloc();
 		if (tx) {
-			usb_cdc_transmit_flush_timer = 0;
-			usb_tx(CDC_TX_ENDPOINT, tx);
+			state->transmit_flush_timer = 0;
+			usb_tx(state->tx_endpoint, tx);
 		} else {
-			usb_cdc_transmit_flush_timer = 1;
+			state->transmit_flush_timer = 1;
 		}
 	}
-	tx_noautoflush = 0;
+	state->tx_noautoflush = 0;
 }
 
-void usb_serial_flush_callback(void)
+void usb_serial_flush_callback(int port)
 {
-	if (tx_noautoflush) return;
-	if (tx_packet) {
-		tx_packet->len = tx_packet->index;
-		usb_tx(CDC_TX_ENDPOINT, tx_packet);
-		tx_packet = NULL;
+	State *const state = &states[port];
+	if (state->tx_noautoflush) return;
+	if (state->tx_packet) {
+		state->tx_packet->len = state->tx_packet->index;
+		usb_tx(state->tx_endpoint, state->tx_packet);
+		state->tx_packet = NULL;
 	} else {
 		usb_packet_t *tx = usb_malloc();
 		if (tx) {
-			usb_tx(CDC_TX_ENDPOINT, tx);
+			usb_tx(state->tx_endpoint, tx);
 		} else {
-			usb_cdc_transmit_flush_timer = 1;
+			state->transmit_flush_timer = 1;
 		}
 	}
 }
-
-
-
-
-#endif // F_CPU
-#endif // CDC_STATUS_INTERFACE && CDC_DATA_INTERFACE
diff --git a/motors/usb/usb_serial.h b/motors/usb/usb_serial.h
index 8367f05..2512adc 100644
--- a/motors/usb/usb_serial.h
+++ b/motors/usb/usb_serial.h
@@ -31,142 +31,48 @@
 #ifndef USBserial_h_
 #define USBserial_h_
 
-#include "usb_desc.h"
-
-#if (defined(CDC_STATUS_INTERFACE) && defined(CDC_DATA_INTERFACE)) || defined(USB_DISABLED)
+#include "motors/usb/usb_desc.h"
 
 #include <inttypes.h>
 
-#if F_CPU >= 20000000 && !defined(USB_DISABLED)
-
 // C language implementation
 #ifdef __cplusplus
 extern "C" {
 #endif
-int usb_serial_getchar(void);
-int usb_serial_peekchar(void);
-int usb_serial_available(void);
-int usb_serial_read(void *buffer, uint32_t size);
-void usb_serial_flush_input(void);
-int usb_serial_putchar(uint8_t c);
-int usb_serial_write(const void *buffer, uint32_t size);
-int usb_serial_write_buffer_free(void);
-void usb_serial_flush_output(void);
-extern uint32_t usb_cdc_line_coding[2];
-extern volatile uint32_t usb_cdc_line_rtsdtr_millis;
-extern volatile uint32_t systick_millis_count;
-extern volatile uint8_t usb_cdc_line_rtsdtr;
-extern volatile uint8_t usb_cdc_transmit_flush_timer;
-extern volatile uint8_t usb_configuration;
+
+void usb_serial_init(void);
+
+// Reads the next character (if any) and returns it. Returns -1 if no characters
+// are available.
+int usb_serial_getchar(int port);
+
+// Returns the next character (if any) or -1.
+int usb_serial_peekchar(int port);
+
+// Reads as many bytes (up to size) as are available now. Returns 0 immediately
+// if no bytes are available. Returns the number of bytes read.
+int usb_serial_read(int port, void *buffer, uint32_t size);
+
+// Drops any unread input until the most recent packet sent.
+void usb_serial_flush_input(int port);
+
+// Writes data. Returns -1 if it times out or size if it succeeds.
+//
+// NOTE: This does not send immediately. The data is buffered
+int usb_serial_write(int port, const void *buffer, uint32_t size);
+
+// Writes a single character. Returns -1 if it times out or 1 if it succeeds.
+static inline int usb_serial_putchar(int port, uint8_t c) {
+  return usb_serial_write(port, &c, 1);
+}
+
+// Immediately flushes all written data.
+//
+// TODO(Brian): What exactly are the semantics here?
+void usb_serial_flush_output(int port);
+
 #ifdef __cplusplus
 }
 #endif
 
-#define USB_SERIAL_DTR  0x01
-#define USB_SERIAL_RTS  0x02
-
-// C++ interface
-#ifdef __cplusplus
-#include "Stream.h"
-class usb_serial_class : public Stream
-{
-public:
-	constexpr usb_serial_class() {}
-        void begin(long) {
-		uint32_t millis_begin = systick_millis_count;
-		while (!(*this)) {
-			// wait up to 2.5 seconds for Arduino Serial Monitor
-			// Yes, this is a long time, but some Windows systems open
-			// the port very slowly.  This wait allows programs for
-			// Arduino Uno to "just work" (without forcing a reboot when
-			// the port is opened), and when no PC is connected the user's
-			// sketch still gets to run normally after this wait time.
-			if ((uint32_t)(systick_millis_count - millis_begin) > 2500) break;
-		}
-	}
-        void end() { /* TODO: flush output and shut down USB port */ };
-        virtual int available() { return usb_serial_available(); }
-        virtual int read() { return usb_serial_getchar(); }
-        virtual int peek() { return usb_serial_peekchar(); }
-        virtual void flush() { usb_serial_flush_output(); }  // TODO: actually wait for data to leave USB...
-        virtual void clear(void) { usb_serial_flush_input(); }
-        virtual size_t write(uint8_t c) { return usb_serial_putchar(c); }
-        virtual size_t write(const uint8_t *buffer, size_t size) { return usb_serial_write(buffer, size); }
-	size_t write(unsigned long n) { return write((uint8_t)n); }
-	size_t write(long n) { return write((uint8_t)n); }
-	size_t write(unsigned int n) { return write((uint8_t)n); }
-	size_t write(int n) { return write((uint8_t)n); }
-	virtual int availableForWrite() { return usb_serial_write_buffer_free(); }
-	using Print::write;
-        void send_now(void) { usb_serial_flush_output(); }
-        uint32_t baud(void) { return usb_cdc_line_coding[0]; }
-        uint8_t stopbits(void) { uint8_t b = usb_cdc_line_coding[1]; if (!b) b = 1; return b; }
-        uint8_t paritytype(void) { return usb_cdc_line_coding[1] >> 8; } // 0=none, 1=odd, 2=even
-        uint8_t numbits(void) { return usb_cdc_line_coding[1] >> 16; }
-        uint8_t dtr(void) { return (usb_cdc_line_rtsdtr & USB_SERIAL_DTR) ? 1 : 0; }
-        uint8_t rts(void) { return (usb_cdc_line_rtsdtr & USB_SERIAL_RTS) ? 1 : 0; }
-        operator bool() { return usb_configuration &&
-		(usb_cdc_line_rtsdtr & (USB_SERIAL_DTR | USB_SERIAL_RTS)) &&
-		((uint32_t)(systick_millis_count - usb_cdc_line_rtsdtr_millis) >= 25);
-	}
-	size_t readBytes(char *buffer, size_t length) {
-		size_t count=0;
-		unsigned long startMillis = millis();
-		do {
-			count += usb_serial_read(buffer + count, length - count);
-			if (count >= length) return count;
-		} while(millis() - startMillis < _timeout);
-		setReadError();
-		return count;
-	}
-
-};
-extern usb_serial_class Serial;
-extern void serialEvent(void);
-#endif // __cplusplus
-
-
-#else  // F_CPU < 20000000
-
-// Allow Arduino programs using Serial to compile, but Serial will do nothing.
-#ifdef __cplusplus
-#include "Stream.h"
-class usb_serial_class : public Stream
-{
-public:
-	constexpr usb_serial_class() {}
-        void begin(long) { };
-        void end() { };
-        virtual int available() { return 0; }
-        virtual int read() { return -1; }
-        virtual int peek() { return -1; }
-        virtual void flush() { }
-        virtual void clear() { }
-        virtual size_t write(uint8_t c) { return 1; }
-        virtual size_t write(const uint8_t *buffer, size_t size) { return size; }
-	size_t write(unsigned long n) { return 1; }
-	size_t write(long n) { return 1; }
-	size_t write(unsigned int n) { return 1; }
-	size_t write(int n) { return 1; }
-	int availableForWrite() { return 0; }
-	using Print::write;
-        void send_now(void) { }
-        uint32_t baud(void) { return 0; }
-        uint8_t stopbits(void) { return 1; }
-        uint8_t paritytype(void) { return 0; }
-        uint8_t numbits(void) { return 8; }
-        uint8_t dtr(void) { return 1; }
-        uint8_t rts(void) { return 1; }
-        operator bool() { return true; }
-};
-
-extern usb_serial_class Serial;
-extern void serialEvent(void);
-#endif // __cplusplus
-
-
-#endif // F_CPU
-
-#endif // CDC_STATUS_INTERFACE && CDC_DATA_INTERFACE
-
 #endif // USBserial_h_