blob: 2c64b6145f4c55c29182729276a784d3bf7ba279 [file] [log] [blame]
Brian Silvermanf91524f2017-09-23 13:15:55 -04001#include "motors/usb/usb.h"
2
3#include <string.h>
4
Brian Silverman4aa83042018-01-05 12:47:31 -08005#include <map>
6
Brian Silvermanf91524f2017-09-23 13:15:55 -04007#include "motors/util.h"
8
9namespace frc971 {
10namespace teensy {
11namespace {
12
13// The mask of interrupts we care about.
14constexpr uint32_t usb_enabled_interrupts() {
15 // Deliberately not turning the sleep interrupt on here because we just
16 // want to ignore that anyways.
17 return USB_INTEN_TOKDNEEN | USB_INTEN_SOFTOKEN | USB_INTEN_ERROREN |
18 USB_INTEN_USBRSTEN;
19}
20
21// The names of all the standard setup requests which come in on endpoint 0.
22namespace standard_setup_requests {
23constexpr int kGetStatus = 0;
24constexpr int kClearFeature = 1;
25constexpr int kSetFeature = 3;
26constexpr int kSetAddress = 5;
27constexpr int kGetDescriptor = 6;
28constexpr int kSetDescriptor = 7;
29constexpr int kGetConfiguration = 8;
30constexpr int kSetConfiguration = 9;
31constexpr int kGetInterface = 10;
32constexpr int kSetInterface = 11;
33constexpr int kSynchFrame = 12;
34} // namespace standard_setup_requests
35
36// The names of the standard feature selectors.
37namespace standard_feature_selectors {
38constexpr int kDeviceRemoteWakeup = 1;
39constexpr int kEndpointHalt = 0;
40constexpr int kTestMode = 2;
41} // namespace standard_feature_selectors
42
43// The names of all the PIDs (Packet IDs) from the USB standard. Note that this
44// USB hardware doesn't expose most of them, especially in device mode.
45enum class UsbPid {
46 kOut = 0x1,
47 kIn = 0x9,
48 kSof = 0x5,
49 kSetup = 0xD,
50 kData0 = 0x3,
51 kData1 = 0xB,
52 kData2 = 0x7,
53 kMData = 0xF,
54 kAck = 0x2,
55 kNak = 0xA,
56 kStall = 0xE,
57 kNYet = 0x6,
58 kPre = 0xC,
59 kErr = 0xC,
60 kSplit = 0x8,
61 kPing = 0x4,
62 kReserved = 0x0,
63};
64
65// The device class for using IADs.
66constexpr uint8_t iad_device_class() { return 0xEF; }
67// The device subclass for using IADs.
68constexpr uint8_t iad_device_subclass() { return 0x02; }
69// The device protocol for using IADs.
70constexpr uint8_t iad_device_protocol() { return 0x01; }
71
Brian Silverman4aa83042018-01-05 12:47:31 -080072// The Microsoft "vendor code" we're going to use. It's pretty arbitrary (just
73// has to not be some other request we want to use).
74constexpr uint8_t microsoft_vendor_code() { return 0x67; }
75
Brian Silvermanf91524f2017-09-23 13:15:55 -040076// The total number of endpoints supported by this hardware.
77constexpr int number_endpoints() { return 16; }
78
Philipp Schrader790cb542023-07-05 21:06:52 -070079__attribute__((aligned(512)))
80BdtEntry usb0_buffer_descriptor_table[number_endpoints() * 2 /* rx/tx */ *
81 2 /* even/odd */];
Brian Silvermanf91524f2017-09-23 13:15:55 -040082
83// Returns the specified BDT entry.
84BdtEntry *MutableBdtEntry(int endpoint, Direction direction, EvenOdd odd) {
85 return &usb0_buffer_descriptor_table[static_cast<uint32_t>(endpoint << 2) |
86 static_cast<uint32_t>(direction) |
87 static_cast<uint32_t>(odd)];
88}
89
90// Returns the BDT entry corresponding to a USBx_STAT value.
91BdtEntry *MutableBdtEntryFromStat(uint8_t stat) {
92 return &usb0_buffer_descriptor_table[static_cast<uint32_t>(stat) >> 2];
93}
94
95// A pointer to the object we're going to ask to handle interrupts.
96UsbDevice *volatile global_usb0_device = nullptr;
97
98} // namespace
99
Brian Silverman19ea60f2018-01-03 21:43:15 -0800100constexpr int UsbDevice::kEndpoint0MaxSize;
101
Brian Silvermanf91524f2017-09-23 13:15:55 -0400102UsbDevice::UsbDevice(int index, uint16_t vendor_id, uint16_t product_id)
103 : index_(index) {
104 // TODO(Brian): Pass index_ into all the register access macros. Also sort out
105 // how to deal with it for the interrupts.
106 assert(index == 0);
107
108 assert(global_usb0_device == nullptr);
109 global_usb0_device = this;
110
111 // Endpoint 0 isn't a normal endpoint, so it doesn't show up in here.
112 endpoint_mapping_.push_back(nullptr);
113
114 // Set up the "String Descriptor Zero, Specifying Languages Supported by the
115 // Device" (aka english_us_code() only).
116 strings_.emplace_back(4, '\0');
117 strings_.back()[0] = 4;
118 strings_.back()[1] = static_cast<uint8_t>(UsbDescriptorType::kString);
119 strings_.back()[2] = english_us_code() & 0xFF;
120 strings_.back()[3] = (english_us_code() >> 8) & 0xFF;
121
122 device_descriptor_ =
123 device_descriptor_list_.CreateDescriptor(18, UsbDescriptorType::kDevice);
Philipp Schrader790cb542023-07-05 21:06:52 -0700124 device_descriptor_->AddUint16(0x0200); // bcdUSB
125 device_descriptor_->AddByte(iad_device_class()); // bDeviceClass
Brian Silvermanf91524f2017-09-23 13:15:55 -0400126 device_descriptor_->AddByte(iad_device_subclass()); // bDeviceSubClass
127 device_descriptor_->AddByte(iad_device_protocol()); // bDeviceProtocol
Philipp Schrader790cb542023-07-05 21:06:52 -0700128 device_descriptor_->AddByte(kEndpoint0MaxSize); // bMaxPacketSize0
129 device_descriptor_->AddUint16(vendor_id); // idVendor
130 device_descriptor_->AddUint16(product_id); // idProduct
Brian Silverman4aa83042018-01-05 12:47:31 -0800131 // Increment this whenever you need Windows boxes to actually pay attention to
132 // changes.
Austin Schuh75c6af42018-03-09 21:16:07 -0800133 device_descriptor_->AddUint16(25); // bcdDevice
Brian Silvermanf91524f2017-09-23 13:15:55 -0400134 // We might overwrite these string descriptor indices later if we get strings
135 // to put there.
136 device_descriptor_->AddByte(0); // iManufacturer
137 device_descriptor_->AddByte(0); // iProduct
138 device_descriptor_->AddByte(0); // iSerialNumber
139 device_descriptor_->AddByte(1); // bNumConfigurations
140
141 config_descriptor_ = config_descriptor_list_.CreateDescriptor(
142 9, UsbDescriptorType::kConfiguration);
143}
144
145UsbDevice::~UsbDevice() {
146 NVIC_DISABLE_IRQ(IRQ_USBOTG);
147 dma_memory_barrier();
148 assert(global_usb0_device == this);
149 global_usb0_device = nullptr;
150}
151
152void UsbDevice::Initialize() {
153 assert(!is_set_up_);
154
155 for (UsbFunction *function : functions_) {
156 function->Initialize();
157 }
158
Brian Silverman4aa83042018-01-05 12:47:31 -0800159 {
160 const uint32_t length = 16 + 24 * functions_.size();
161 microsoft_extended_id_descriptor_.resize(length);
162 int index = 0;
163
164 // dwLength
165 microsoft_extended_id_descriptor_[index++] = length & 0xFF;
166 microsoft_extended_id_descriptor_[index++] = (length >> UINT32_C(8)) & 0xFF;
167 microsoft_extended_id_descriptor_[index++] =
168 (length >> UINT32_C(16)) & 0xFF;
169 microsoft_extended_id_descriptor_[index++] =
170 (length >> UINT32_C(24)) & 0xFF;
171
172 // bcdVersion
173 microsoft_extended_id_descriptor_[index++] = 0x00;
174 microsoft_extended_id_descriptor_[index++] = 0x01;
175
176 // wIndex
177 microsoft_extended_id_descriptor_[index++] =
178 microsoft_feature_descriptors::kExtendedCompatibilityId;
179 microsoft_extended_id_descriptor_[index++] = 0;
180
181 // bCount
182 microsoft_extended_id_descriptor_[index++] = functions_.size();
183
184 // Reserved
185 index += 7;
186
187 for (UsbFunction *function : functions_) {
188 // bFirstInterfaceNumber
189 microsoft_extended_id_descriptor_[index++] = function->first_interface_;
190
191 // Reserved
192 index++;
193
194 // compatibleID and subCompatibleID
195 microsoft_extended_id_descriptor_.replace(
196 index, 16, function->MicrosoftExtendedCompatibleId());
197 index += 16;
198
199 // Reserved
200 index += 6;
201 }
202
203 assert(index == length);
204 }
205
Brian Silvermanf91524f2017-09-23 13:15:55 -0400206 config_descriptor_->AddUint16(
207 config_descriptor_list_.CurrentSize()); // wTotalLength
208 config_descriptor_->AddByte(interface_mapping_.size()); // bNumInterfaces
209 config_descriptor_->AddByte(1); // bConfigurationValue
210 // Doesn't seem to be much point naming our one and only configuration.
211 config_descriptor_->AddByte(0); // iConfiguration
212 config_descriptor_->AddByte((1 << 7) /* Reserved */ |
213 (1 << 6) /* Self-powered */); // bmAttribute
Philipp Schrader790cb542023-07-05 21:06:52 -0700214 config_descriptor_->AddByte(2 /* 4mA */); // bMaxPower
Brian Silvermanf91524f2017-09-23 13:15:55 -0400215
216 device_descriptor_.reset();
217 config_descriptor_.reset();
218 device_descriptor_list_.CheckFinished();
219 config_descriptor_list_.CheckFinished();
220 is_set_up_ = true;
221
222 // Make sure all the buffer descriptors are clear.
223 for (int i = 0; i < number_endpoints(); ++i) {
224 for (Direction direction : {Direction::kTx, Direction::kRx}) {
225 for (EvenOdd odd : {EvenOdd::kOdd, EvenOdd::kEven}) {
226 MutableBdtEntry(i, direction, odd)->buffer_descriptor = 0;
227 MutableBdtEntry(i, direction, odd)->address = nullptr;
228 }
229 }
230 }
231 dma_memory_barrier();
232
233 // The other startup code handles getting the incoming 48MHz clock running.
234 SIM_SCGC4 |= SIM_SCGC4_USBOTG;
235 MPU_RGDAAC0 |= 0x03000000;
236
237 // Reset it.
238 USB0_USBTRC0 = USB_USBTRC_USBRESET;
239 // TRM says to wait "two USB clock cycles", so assume that's at 48MHz and then
240 // round up, being pessimistic in assuming each read from the peripheral is
241 // only a single core clock. This wildly overapproximates how long we need to
242 // wait, but whatever.
243 for (int i = 0; i < ((F_CPU / 48000000) + 1) * 2; ++i) {
244 while ((USB0_USBTRC0 & USB_USBTRC_USBRESET) != 0) {
245 }
246 }
247
248 USB0_BDTPAGE1 =
249 reinterpret_cast<uintptr_t>(&usb0_buffer_descriptor_table[0]) >> 8;
250 USB0_BDTPAGE2 =
251 reinterpret_cast<uintptr_t>(&usb0_buffer_descriptor_table[0]) >> 16;
252 USB0_BDTPAGE3 =
253 reinterpret_cast<uintptr_t>(&usb0_buffer_descriptor_table[0]) >> 24;
254
255 // The Quick Reference User Guide says to clear all the interrupts.
256 ClearInterrupts();
257 USB0_OTGISTAT = USB_OTGISTAT_ONEMSEC | USB_OTGISTAT_LINE_STATE_CHG;
258
259 // Now enable the module.
260 USB0_CTL = USB_CTL_USBENSOFEN;
261
262 // Un-suspend the transceiver and disable weak pulldowns.
263 USB0_USBCTRL = 0;
264 // And enable the D+ pullup which indicates we're a full-speed device.
265 USB0_CONTROL = USB_CONTROL_DPPULLUPNONOTG;
266
267 // Enable the reset interrupt (which is the first one we care about).
268 USB0_INTEN = USB_INTEN_USBRSTEN;
269
270 dma_memory_barrier();
271 NVIC_ENABLE_IRQ(IRQ_USBOTG);
272}
273
274void usb_isr(void) {
275 UsbDevice *const usb0_device = global_usb0_device;
276 if (usb0_device == nullptr) {
277 NVIC_DISABLE_IRQ(IRQ_USBOTG);
278 } else {
279 usb0_device->HandleInterrupt();
280 }
281}
282
283void UsbDevice::ClearInterrupts() {
284 USB0_ISTAT = USB_ISTAT_ATTACH | USB_ISTAT_RESUME | USB_ISTAT_SLEEP |
285 USB_ISTAT_TOKDNE | USB_ISTAT_SOFTOK | USB_ISTAT_ERROR |
286 USB_ISTAT_USBRST;
287 USB0_ERRSTAT = USB_ERRSTAT_BTSERR | USB_ERRSTAT_DMAERR | USB_ERRSTAT_BTOERR |
288 USB_ERRSTAT_DFN8 | USB_ERRSTAT_CRC16 | USB_ERRSTAT_CRC5EOF |
289 USB_ERRSTAT_PIDERR;
290}
291
292void UsbDevice::HandleInterrupt() {
293 while (true) {
294 const uint32_t status = USB0_ISTAT;
295 if ((status & usb_enabled_interrupts()) == 0) {
296 return;
297 }
298
299 // If we just got a start-of-frame token, then ask all the functions what to
300 // do.
301 if (status & USB_ISTAT_SOFTOK) {
302 // TODO(Brian): Actually ask the functions, maybe only if we're
303 // configured.
304 USB0_ISTAT = USB_ISTAT_SOFTOK;
305 }
306
307 // If we just finished processing a token.
308 if (status & USB_ISTAT_TOKDNE) {
309 const uint8_t stat = USB0_STAT;
Brian Silverman69f96c22017-11-01 02:54:02 -0400310 USB0_ISTAT = USB_ISTAT_TOKDNE;
Brian Silvermanf91524f2017-09-23 13:15:55 -0400311 const int endpoint = G_USB_STAT_ENDP(stat);
312
313 if (endpoint == 0) {
314 HandleEndpoint0Token(stat);
315 } else {
316 BdtEntry *const bdt_entry = MutableBdtEntryFromStat(stat);
317 const UsbPid pid = G_USB_BD_PID(bdt_entry->buffer_descriptor);
318 UsbFunction *const function = endpoint_mapping_[endpoint];
319 if (function == nullptr) {
320 // Should never happen, so stall if we do get here somehow.
321 StallEndpoint(endpoint);
322 } else {
323 switch (pid) {
324 case UsbPid::kOut:
325 function->HandleOutFinished(endpoint, bdt_entry);
326 break;
327
328 case UsbPid::kIn:
329 function->HandleInFinished(
330 endpoint, bdt_entry,
331 (stat & M_USB_STAT_ODD) ? EvenOdd::kOdd : EvenOdd::kEven);
332 break;
333
334 case UsbPid::kSetup:
335 default:
336 // Should never happen, so stall if we do get here somehow.
337 StallEndpoint(endpoint);
338 break;
339 }
340 }
341 }
Brian Silvermanf91524f2017-09-23 13:15:55 -0400342 }
343
344 if (status & USB_ISTAT_USBRST) {
345 // Use DATA0 for all endpoints.
346 USB0_CTL = USB_CTL_ODDRST;
347 endpoint0_tx_odd_ = EvenOdd::kEven;
348 endpoint0_tx_toggle_ = Data01::kData0;
349
350 for (UsbFunction *function : functions_) {
351 function->HandleReset();
352 }
353
354 MutableBdtEntry(0, Direction::kRx, EvenOdd::kEven)->buffer_descriptor =
355 M_USB_BD_OWN | M_USB_BD_DTS | V_USB_BD_BC(kEndpoint0MaxSize);
356 MutableBdtEntry(0, Direction::kRx, EvenOdd::kEven)->address =
357 &endpoint0_receive_buffer_[0][0];
358
359 MutableBdtEntry(0, Direction::kRx, EvenOdd::kOdd)->buffer_descriptor =
360 M_USB_BD_OWN | M_USB_BD_DTS | V_USB_BD_BC(kEndpoint0MaxSize);
361 MutableBdtEntry(0, Direction::kRx, EvenOdd::kOdd)->address =
362 &endpoint0_receive_buffer_[1][0];
363
364 MutableBdtEntry(0, Direction::kTx, EvenOdd::kEven)->buffer_descriptor = 0;
365 MutableBdtEntry(0, Direction::kTx, EvenOdd::kOdd)->buffer_descriptor = 0;
366
367 USB0_ENDPT0 = USB_ENDPT_EPRXEN | USB_ENDPT_EPTXEN | USB_ENDPT_EPHSHK;
368
369 ClearInterrupts();
370
371 // Set the address to 0 for enumeration.
372 USB0_ADDR = 0;
373 new_address_ = 0;
374
375 endpoint0_data_ = nullptr;
376 endpoint0_data_left_ = 0;
377
378 USB0_INTEN = usb_enabled_interrupts();
379 USB0_ERREN = USB_ERREN_BTSERREN | USB_ERREN_DMAERREN |
380 USB_ERREN_BTOERREN | USB_ERREN_DFN8EN | USB_ERREN_CRC16EN |
381 USB_ERREN_CRC5EOFEN | USB_ERREN_PIDERREN;
382
383 // Start the peripheral going.
384 dma_memory_barrier();
385 USB0_CTL = USB_CTL_USBENSOFEN;
386
387 continue;
388 }
389
390 // TODO(Brian): Handle errors more intelligently.
391 if (status & USB_ISTAT_ERROR) {
392 const uint8_t error = USB0_ERRSTAT;
393 USB0_ERRSTAT = error;
394 USB0_ISTAT = USB_ISTAT_ERROR;
395 }
396 }
397}
398
399void UsbDevice::HandleEndpoint0Token(const uint8_t stat) {
400 BdtEntry *const bdt_entry = MutableBdtEntryFromStat(stat);
401 const UsbPid pid = G_USB_BD_PID(bdt_entry->buffer_descriptor);
402 switch (pid) {
403 case UsbPid::kSetup:
404 // Unstall it if it was previously stalled.
405 USB0_ENDPT0 = USB_ENDPT_EPRXEN | USB_ENDPT_EPTXEN | USB_ENDPT_EPHSHK;
406
407 SetupPacket setup_packet;
408 memcpy(&setup_packet, bdt_entry->address, sizeof(setup_packet));
409
410 // Give the buffer back now.
411 dma_memory_barrier();
412 // Next IN and OUT packet for this endpoint (data stage/status stage)
413 // should both be DATA1.
Brian Silvermanf91524f2017-09-23 13:15:55 -0400414 MutableBdtEntryFromStat(stat ^ M_USB_STAT_ODD)->buffer_descriptor =
415 M_USB_BD_OWN | M_USB_BD_DTS | V_USB_BD_BC(kEndpoint0MaxSize) |
416 M_USB_BD_DATA1;
417 endpoint0_tx_toggle_ = Data01::kData1;
418
Brian Silverman69f96c22017-11-01 02:54:02 -0400419 // Give this buffer back. It should be DATA0 because it'll be the second
420 // received packet.
421 bdt_entry->buffer_descriptor =
422 M_USB_BD_OWN | M_USB_BD_DTS | V_USB_BD_BC(kEndpoint0MaxSize);
423
Brian Silvermanf91524f2017-09-23 13:15:55 -0400424 // TODO(Brian): Tell the functions a new setup packet is starting.
425 // CdcTty: next_endpoint0_out_ = NextEndpoint0Out::kNone;
426
427 // Forget about any pending transactions on this endpoint. There shouldn't
428 // be any, so if we think there are something's out of sync and we should
429 // just drop it. Important to do this before clearing TXD_SUSPEND in
430 // USBx_CTL. Standard says "If a Setup transaction is received by an
431 // endpoint before a previously initiated control transfer is completed,
432 // the device must abort the current transfer/operation".
433 endpoint0_data_ = nullptr;
434 endpoint0_data_left_ = 0;
435 MutableBdtEntry(0, Direction::kTx, EvenOdd::kEven)->buffer_descriptor = 0;
436 MutableBdtEntry(0, Direction::kTx, EvenOdd::kOdd)->buffer_descriptor = 0;
437
438 HandleEndpoint0SetupPacket(setup_packet);
439
440 break;
441
442 case UsbPid::kOut:
Philipp Schrader790cb542023-07-05 21:06:52 -0700443 for (UsbFunction *function : functions_) {
444 switch (function->HandleEndpoint0OutPacket(
445 bdt_entry->address, G_USB_BD_BC(bdt_entry->buffer_descriptor))) {
Brian Silvermanf91524f2017-09-23 13:15:55 -0400446 case SetupResponse::kIgnored:
447 break;
448 case SetupResponse::kHandled:
449 dma_memory_barrier();
450 bdt_entry->buffer_descriptor =
451 M_USB_BD_OWN | M_USB_BD_DTS | V_USB_BD_BC(kEndpoint0MaxSize);
452 return;
453 case SetupResponse::kStall:
454 bdt_entry->buffer_descriptor =
455 M_USB_BD_OWN | M_USB_BD_DTS | V_USB_BD_BC(kEndpoint0MaxSize);
456 StallEndpoint0();
457 return;
458 }
459 }
460 bdt_entry->buffer_descriptor =
461 M_USB_BD_OWN | M_USB_BD_DTS | V_USB_BD_BC(kEndpoint0MaxSize);
462 StallEndpoint0();
463 return;
464
465 case UsbPid::kIn:
466 // The functions are allowed to queue data in {endpoint0_data_,
467 // endpoint0_data_left_}, so this case deals with sending their data too.
468
469 // An IN transaction completed, so set up for the next one if appropriate.
470 if (!BufferEndpoint0TxPacket()) {
471 // After we're done, any further requests from the host should result in
472 // stalls (until the next setup token).
473 // TODO(Brian): Keep track of which direction it is and how much we've
474 // finished so we actually know when to stall it, both here and for
475 // kOut tokens.
Philipp Schrader790cb542023-07-05 21:06:52 -0700476 // StallEndpoint0();
Brian Silvermanf91524f2017-09-23 13:15:55 -0400477 }
478
479 // If we have a new address, there is nothing left in the setup request
480 // besides a single IN packet forming the status stage, so we know the
481 // changes must be done now.
482 if (new_address_ != 0) {
483 USB0_ADDR = new_address_;
484 new_address_ = 0;
485 }
486
487 break;
488
489 default:
490 // Should never happen, but give the buffer back anyways if necessary.
491 if (!(bdt_entry->buffer_descriptor & M_USB_BD_OWN)) {
492 bdt_entry->buffer_descriptor =
493 M_USB_BD_OWN | M_USB_BD_DTS | V_USB_BD_BC(kEndpoint0MaxSize);
494 }
495 break;
496 }
497
498 // Clear the TXD_SUSPEND flag.
499 dma_memory_barrier();
500 USB0_CTL = USB_CTL_USBENSOFEN;
501}
502
503void UsbDevice::HandleEndpoint0SetupPacket(const SetupPacket &setup_packet) {
504 const bool in = setup_packet.request_type & M_SETUP_REQUEST_TYPE_IN;
505 const uint8_t recipient =
506 G_SETUP_REQUEST_TYPE_RECIPIENT(setup_packet.request_type);
507 switch (G_SETUP_REQUEST_TYPE_TYPE(setup_packet.request_type)) {
508 case SetupRequestType::kStandard:
509 switch (setup_packet.request) {
510 case standard_setup_requests::kSetAddress:
511 if (in || recipient != standard_setup_recipients::kDevice ||
512 setup_packet.index != 0 || setup_packet.length != 0) {
513 break;
514 }
515 new_address_ = setup_packet.value;
516 SendEmptyEndpoint0Packet();
517 return;
518
519 case standard_setup_requests::kSetConfiguration:
520 if (in || recipient != standard_setup_recipients::kDevice ||
521 setup_packet.index != 0 || setup_packet.length != 0) {
522 break;
523 }
524 configuration_ = setup_packet.value;
525
526 // No need to mess with endpoint0_tx_toggle_ because we reset it with
527 // each setup packet anyways.
528
529 for (int endpoint = 0;
530 endpoint < static_cast<int>(endpoint_mapping_.size());
531 ++endpoint) {
532 if (endpoint_mapping_[endpoint]) {
533 endpoint_mapping_[endpoint]->HandleConfigured(endpoint);
534 }
535 }
536
537 SendEmptyEndpoint0Packet();
538 return;
539
540 case standard_setup_requests::kClearFeature:
541 if (in || setup_packet.length != 0) {
542 break;
543 }
544 if (recipient == standard_setup_recipients::kEndpoint &&
545 setup_packet.value == standard_feature_selectors::kEndpointHalt) {
546 const int endpoint =
547 G_SETUP_REQUEST_INDEX_ENDPOINT(setup_packet.index);
548 // Our endpoint 0 doesn't support the halt feature because that's
549 // weird and not recommended by the standard.
550 if (endpoint == 0) {
551 break;
552 }
553 if (endpoint >= number_endpoints()) {
554 break;
555 }
556 USB0_ENDPTn(endpoint) &= ~USB_ENDPT_EPSTALL;
557 if (endpoint_mapping_[endpoint] != nullptr) {
558 endpoint_mapping_[endpoint]->HandleConfigured(endpoint);
559 }
560 SendEmptyEndpoint0Packet();
561 return;
562 }
563 // We should never get kDeviceRemoteWakeup because we don't advertise
564 // support for it in our configuration descriptors.
565 // We should never get kTestMode because we're not high-speed.
566 break;
567
568 case standard_setup_requests::kSetFeature:
569 if (in || setup_packet.length != 0) {
570 break;
571 }
572 if (recipient == standard_setup_recipients::kEndpoint &&
573 setup_packet.value == standard_feature_selectors::kEndpointHalt) {
574 const int endpoint =
575 G_SETUP_REQUEST_INDEX_ENDPOINT(setup_packet.index);
576 // Our endpoint 0 doesn't support the halt feature because that's
577 // weird and not recommended by the standard.
578 if (endpoint == 0) {
579 break;
580 }
581 if (endpoint >= number_endpoints()) {
582 break;
583 }
584 StallEndpoint(endpoint);
585 // TODO(Brian): Tell the appropriate function it's now stalled.
586 SendEmptyEndpoint0Packet();
587 return;
588 }
589 // We should never get kDeviceRemoteWakeup because we don't advertise
590 // support for it in our configuration descriptors.
591 // We should never get kTestMode because we're not high-speed.
592 break;
593
594 case standard_setup_requests::kGetConfiguration:
595 if (!in || recipient != standard_setup_recipients::kDevice ||
596 setup_packet.index != 0 || setup_packet.length != 1) {
597 break;
598 }
599 endpoint0_transmit_buffer_[0] = configuration_;
600 QueueEndpoint0Data(endpoint0_transmit_buffer_, 1);
601 return;
602
603 case standard_setup_requests::kGetInterface:
604 if (!in || recipient != standard_setup_recipients::kInterface ||
605 setup_packet.value != 0 || setup_packet.length != 1) {
606 break;
607 }
608 // Standard says it's unspecified in the default state and must
609 // respond with an error in the address state, so just do an error for
610 // both of them.
611 if (configuration_ == 0) {
612 break;
613 }
614 // TODO(Brian): Ask the appropriate function what alternate setting
615 // the interface has, and stall if there isn't one.
616 endpoint0_transmit_buffer_[0] = 0;
617 QueueEndpoint0Data(endpoint0_transmit_buffer_, 1);
618 return;
619
620 case standard_setup_requests::kSetInterface:
621 if (in || recipient != standard_setup_recipients::kInterface ||
622 setup_packet.length != 0) {
623 break;
624 }
625 // Standard says it's unspecified in the default state and must
626 // respond with an error in the address state, so just do an error for
627 // both of them.
628 if (configuration_ == 0) {
629 break;
630 }
631
632 // TODO(Brian): Pass to the appropriate function instead.
633 if (setup_packet.value != 0) {
634 break;
635 }
636 SendEmptyEndpoint0Packet();
637 return;
638
639 case standard_setup_requests::kGetStatus:
640 if (!in || setup_packet.value != 0 || setup_packet.length != 2) {
641 break;
642 }
643 if (recipient == standard_setup_recipients::kDevice) {
644 if (setup_packet.index != 0) {
645 break;
646 }
647 // Say that we're currently self powered.
648 endpoint0_transmit_buffer_[0] = 1;
649 endpoint0_transmit_buffer_[1] = 0;
650 QueueEndpoint0Data(endpoint0_transmit_buffer_, 2);
651 return;
652 }
653 if ((recipient == standard_setup_recipients::kInterface &&
654 setup_packet.index == 0) ||
655 (recipient == standard_setup_recipients::kEndpoint &&
656 G_SETUP_REQUEST_INDEX_ENDPOINT(setup_packet.index) == 0)) {
657 endpoint0_transmit_buffer_[0] = 0;
658 endpoint0_transmit_buffer_[1] = 0;
659 QueueEndpoint0Data(endpoint0_transmit_buffer_, 2);
660 return;
661 }
662 // Standard says it's unspecified in the default state and must
663 // respond with an error in the address state, so just do an error
664 // for both of them.
665 if (configuration_ == 0) {
666 break;
667 }
668
669 if (recipient == standard_setup_recipients::kInterface) {
670 // TODO(Brian): Check if it's actually an interface we have?
671 endpoint0_transmit_buffer_[0] = 0;
672 endpoint0_transmit_buffer_[1] = 0;
673 QueueEndpoint0Data(endpoint0_transmit_buffer_, 2);
674 return;
675 }
676
677 if (recipient == standard_setup_recipients::kEndpoint) {
678 const int endpoint =
679 G_SETUP_REQUEST_INDEX_ENDPOINT(setup_packet.index);
680 // TODO(Brian): Check if it's actually an endpoint we have?
681 if (USB0_ENDPTn(endpoint) & USB_ENDPT_EPSTALL) {
682 endpoint0_transmit_buffer_[0] = 1;
683 } else {
684 endpoint0_transmit_buffer_[0] = 0;
685 }
686 endpoint0_transmit_buffer_[1] = 0;
687 QueueEndpoint0Data(endpoint0_transmit_buffer_, 2);
688 return;
689 }
690 break;
691
692 case standard_setup_requests::kSetDescriptor:
693 // Not implementing anything for this.
694 break;
695
696 case standard_setup_requests::kSynchFrame:
697 // We don't implement any classes which use this.
698 break;
699
700 case standard_setup_requests::kGetDescriptor:
Brian Silvermand930f282017-11-04 23:09:12 -0400701 if (!in) {
Brian Silvermanf91524f2017-09-23 13:15:55 -0400702 break;
703 }
Brian Silvermand930f282017-11-04 23:09:12 -0400704
Brian Silvermanf91524f2017-09-23 13:15:55 -0400705 const uint8_t descriptor_type_byte = (setup_packet.value >> 8) & 0xFF;
Brian Silvermand930f282017-11-04 23:09:12 -0400706 if (G_DESCRIPTOR_TYPE_TYPE(descriptor_type_byte) !=
707 standard_descriptor_type_types::kStandard) {
708 for (UsbFunction *function : functions_) {
709 switch (function->HandleGetDescriptor(setup_packet)) {
710 case SetupResponse::kIgnored:
711 continue;
712 case SetupResponse::kHandled:
713 return;
714 case SetupResponse::kStall:
715 break;
716 }
717 break;
718 }
719 break;
720 }
721
722 if (recipient != standard_setup_recipients::kDevice) {
723 break;
724 }
Brian Silvermanf91524f2017-09-23 13:15:55 -0400725 if (descriptor_type_byte < kUsbDescriptorTypeMin ||
726 descriptor_type_byte > kUsbDescriptorTypeMax) {
727 break;
728 }
729 const UsbDescriptorType descriptor_type =
730 static_cast<UsbDescriptorType>(descriptor_type_byte);
731 const uint8_t descriptor_index = setup_packet.value & 0xFF;
732 switch (descriptor_type) {
733 case UsbDescriptorType::kDevice:
734 if (setup_packet.index != 0 || descriptor_index != 0) {
735 break;
736 }
737 QueueEndpoint0Data(
738 device_descriptor_list_.data_.data(),
739 ::std::min<int>(setup_packet.length,
740 device_descriptor_list_.data_.size()));
741 return;
742
743 case UsbDescriptorType::kConfiguration:
744 if (setup_packet.index != 0 || descriptor_index != 0) {
745 break;
746 }
747 QueueEndpoint0Data(
748 config_descriptor_list_.data_.data(),
749 ::std::min<int>(setup_packet.length,
750 config_descriptor_list_.data_.size()));
751 return;
752
753 case UsbDescriptorType::kString:
Brian Silverman4aa83042018-01-05 12:47:31 -0800754 // Skip any other checks on the other fields. Who knows what
755 // Microsoft is going to set them to; not like they document it
756 // anywhere obvious...
757 if (descriptor_index == 0xEE && setup_packet.index == 0) {
Philipp Schrader790cb542023-07-05 21:06:52 -0700758 static uint8_t kMicrosoftOsStringDescriptor[] = {
759 0x12, // bLength
760 static_cast<uint8_t>(
761 UsbDescriptorType::kString), // bDescriptorType
762 0x4D,
763 0x00,
764 0x53,
765 0x00,
766 0x46,
767 0x00,
768 0x54,
769 0x00,
770 0x31,
771 0x00,
772 0x30,
773 0x00,
774 0x30,
775 0x00, // qwSignature
776 microsoft_vendor_code(), // bMS_VendorCode
777 0x00 // bPad
778 };
Brian Silverman4aa83042018-01-05 12:47:31 -0800779 QueueEndpoint0Data(
780 reinterpret_cast<char *>(kMicrosoftOsStringDescriptor),
781 ::std::min<int>(setup_packet.length,
782 sizeof(kMicrosoftOsStringDescriptor)));
783 return;
784 }
Brian Silvermand930f282017-11-04 23:09:12 -0400785 if (descriptor_index != 0 &&
786 setup_packet.index != english_us_code()) {
Brian Silvermanf91524f2017-09-23 13:15:55 -0400787 break;
788 }
789 if (descriptor_index >= strings_.size()) {
790 break;
791 }
792 QueueEndpoint0Data(
793 strings_[descriptor_index].data(),
794 ::std::min<int>(setup_packet.length,
795 strings_[descriptor_index].size()));
796 return;
797
798 default:
799 // TODO(Brian): Handle other types of descriptor too.
800 break;
801 }
802 }
803 break;
804
Brian Silverman4aa83042018-01-05 12:47:31 -0800805 case SetupRequestType::kVendor:
806 switch (setup_packet.request) {
807 case microsoft_vendor_code():
808 if (!in) {
809 break;
810 }
811
812 switch (recipient) {
813 case standard_setup_recipients::kDevice:
814 if (setup_packet.value != 0) {
815 // Ignoring weird things and descriptors larger than 64K for
816 // now.
817 break;
818 }
819 switch (setup_packet.index) {
820 case microsoft_feature_descriptors::kExtendedCompatibilityId:
821 QueueEndpoint0Data(
822 microsoft_extended_id_descriptor_.data(),
823 ::std::min<int>(
824 setup_packet.length,
825 microsoft_extended_id_descriptor_.size()));
826 return;
827 }
828 break;
829
830 case standard_setup_recipients::kInterface:
831 switch (setup_packet.index) {
832 case microsoft_feature_descriptors::kExtendedProperties:
833 const int interface = setup_packet.value & 0xFF;
834 const int page_number = (setup_packet.value >> 8) & 0xFF;
835
836 if (page_number != 0) {
837 // Ignoring weird things and descriptors larger than 64K for
838 // now.
839 break;
840 }
841
842 const UsbFunction *const function =
843 interface_mapping_[interface];
844 const ::std::string &descriptor =
845 function->microsoft_extended_property_descriptor_;
846 if (descriptor.empty() ||
847 interface != function->first_interface_) {
848 break;
849 }
850 QueueEndpoint0Data(
851 descriptor.data(),
852 ::std::min<int>(setup_packet.length, descriptor.size()));
853 return;
854 }
855 break;
856 }
857 break;
858 }
859 break;
860
Brian Silvermanf91524f2017-09-23 13:15:55 -0400861 default:
862 for (UsbFunction *function : functions_) {
863 switch (function->HandleEndpoint0SetupPacket(setup_packet)) {
864 case SetupResponse::kIgnored:
865 continue;
866 case SetupResponse::kHandled:
867 return;
868 case SetupResponse::kStall:
869 break;
870 }
871 break;
872 }
873 break;
874 }
875
876 StallEndpoint0();
877}
878
879// We're supposed to continue returning stalls until the next kSetup packet.
880// Code might continue putting stuff in the TX buffers, but the hardware won't
881// actually send it as long as the EPSTALL bit is set.
882void UsbDevice::StallEndpoint0() {
883 USB0_ENDPT0 = USB_ENDPT_EPSTALL | USB_ENDPT_EPRXEN | USB_ENDPT_EPTXEN |
884 USB_ENDPT_EPHSHK;
885}
886
887bool UsbDevice::BufferEndpoint0TxPacket() {
888 if (endpoint0_data_ == nullptr) {
889 return false;
890 }
891
892 const int to_transmit = ::std::min(endpoint0_data_left_, kEndpoint0MaxSize);
893 BdtEntry *const tx_bdt_entry =
894 MutableBdtEntry(0, Direction::kTx, endpoint0_tx_odd_);
895 // const_cast is safe because the hardware is only going to read from
896 // this, not write.
897 tx_bdt_entry->address =
898 const_cast<void *>(static_cast<const void *>(endpoint0_data_));
899 dma_memory_barrier();
900 tx_bdt_entry->buffer_descriptor =
901 V_USB_BD_BC(to_transmit) | static_cast<uint32_t>(endpoint0_tx_toggle_) |
902 M_USB_BD_OWN | M_USB_BD_DTS;
903
904 endpoint0_tx_odd_ = EvenOddInverse(endpoint0_tx_odd_);
905 endpoint0_tx_toggle_ = Data01Inverse(endpoint0_tx_toggle_);
906
907 endpoint0_data_ += to_transmit;
908 endpoint0_data_left_ -= to_transmit;
909 if (to_transmit < kEndpoint0MaxSize) {
910 endpoint0_data_ = nullptr;
911 }
912
913 return true;
914}
915
916void UsbDevice::SendEmptyEndpoint0Packet() {
917 // Really doesn't matter what we put here as long as it's not nullptr.
918 endpoint0_data_ = reinterpret_cast<char *>(this);
919 endpoint0_data_left_ = 0;
920 BufferEndpoint0TxPacket();
921}
922
923void UsbDevice::QueueEndpoint0Data(const char *data, int size) {
924 endpoint0_data_ = data;
925 endpoint0_data_left_ = size;
926 // There are 2 TX buffers, so fill them both up.
927 BufferEndpoint0TxPacket();
928 BufferEndpoint0TxPacket();
929}
930
931void UsbDevice::StallEndpoint(int endpoint) {
932 for (Direction direction : {Direction::kTx, Direction::kRx}) {
933 for (EvenOdd odd : {EvenOdd::kOdd, EvenOdd::kEven}) {
934 MutableBdtEntry(endpoint, direction, odd)->buffer_descriptor = 0;
935 dma_memory_barrier();
936 MutableBdtEntry(endpoint, direction, odd)->address = nullptr;
937 }
938 }
939 USB0_ENDPTn(endpoint) |= USB_ENDPT_EPSTALL;
940}
941
942void UsbDevice::ConfigureEndpointFor(int endpoint, bool rx, bool tx,
943 bool handshake) {
944 uint8_t control = 0;
945 if (rx) {
946 control |= USB_ENDPT_EPRXEN;
947 }
948 if (tx) {
949 control |= USB_ENDPT_EPTXEN;
950 }
951 if (handshake) {
952 control |= USB_ENDPT_EPHSHK;
953 }
954 USB0_ENDPTn(endpoint) = control;
955}
956
957int UsbFunction::AddEndpoint() {
958 const int r = device_->endpoint_mapping_.size();
959 assert(r < number_endpoints());
960 device_->endpoint_mapping_.push_back(this);
961 return r;
962}
963
964int UsbFunction::AddInterface() {
965 const int r = device_->interface_mapping_.size();
966 // bInterfaceNumber is only one byte.
967 assert(r < 255);
968 device_->interface_mapping_.push_back(this);
969 return r;
970}
971
Brian Silverman4aa83042018-01-05 12:47:31 -0800972void UsbFunction::CreateIadDescriptor(int first_interface, int interface_count,
973 int function_class, int function_subclass,
974 int function_protocol,
975 const ::std::string &function) {
976 first_interface_ = first_interface;
977 const auto iad_descriptor = CreateDescriptor(
978 iad_descriptor_length(), UsbDescriptorType::kInterfaceAssociation);
979 iad_descriptor->AddByte(first_interface); // bFirstInterface
980 iad_descriptor->AddByte(interface_count); // bInterfaceCount
981 iad_descriptor->AddByte(function_class); // bFunctionClass
982 iad_descriptor->AddByte(function_subclass); // bFunctionSubClass
983 iad_descriptor->AddByte(function_protocol); // bFunctionProtocol
984 iad_descriptor->AddByte(device()->AddString(function)); // iFunction
985}
986
987void UsbFunction::SetMicrosoftDeviceInterfaceGuids(const ::std::string &guids) {
988 ::std::map<::std::string, ::std::string> properties;
989 properties["DeviceInterfaceGUIDs"] = guids + ::std::string(1, '\0');
990 ::std::string *const descriptor = &microsoft_extended_property_descriptor_;
991
992 uint32_t length = 10;
993 for (auto &pair : properties) {
994 length += 14;
995 length += (pair.first.size() + 1) * 2;
996 length += (pair.second.size() + 1) * 2;
997 }
998 descriptor->resize(length);
999 int index = 0;
1000
1001 // dwLength
1002 (*descriptor)[index++] = length & 0xFF;
1003 (*descriptor)[index++] = (length >> UINT32_C(8)) & 0xFF;
1004 (*descriptor)[index++] = (length >> UINT32_C(16)) & 0xFF;
1005 (*descriptor)[index++] = (length >> UINT32_C(24)) & 0xFF;
1006
1007 // bcdVersion
1008 (*descriptor)[index++] = 0x00;
1009 (*descriptor)[index++] = 0x01;
1010
1011 // wIndex
1012 (*descriptor)[index++] = microsoft_feature_descriptors::kExtendedProperties;
1013 (*descriptor)[index++] = 0;
1014
1015 // wCount
1016 (*descriptor)[index++] = properties.size() & 0xFF;
1017 (*descriptor)[index++] = (properties.size() >> 8) & 0xFF;
1018
1019 for (auto &pair : properties) {
1020 const uint32_t size = 14 + (pair.first.size() + pair.second.size() + 2) * 2;
1021 // dwSize
1022 (*descriptor)[index++] = size & 0xFF;
1023 (*descriptor)[index++] = (size >> UINT32_C(8)) & 0xFF;
1024 (*descriptor)[index++] = (size >> UINT32_C(16)) & 0xFF;
1025 (*descriptor)[index++] = (size >> UINT32_C(24)) & 0xFF;
1026
1027 // Need to get this from the map if we ever do others in the future.
1028 const uint32_t data_type = 7; // REG_MULTI_SZ
1029 // dwPropertyDataType
1030 (*descriptor)[index++] = data_type & 0xFF;
1031 (*descriptor)[index++] = (data_type >> UINT32_C(8)) & 0xFF;
1032 (*descriptor)[index++] = (data_type >> UINT32_C(16)) & 0xFF;
1033 (*descriptor)[index++] = (data_type >> UINT32_C(24)) & 0xFF;
1034
1035 // wPropertyNameLength
1036 (*descriptor)[index++] = ((pair.first.size() + 1) * 2) & 0xFF;
1037 (*descriptor)[index++] = (((pair.first.size() + 1) * 2) >> 8) & 0xFF;
1038
1039 // bPropertyName
1040 for (size_t i = 0; i < pair.first.size(); ++i) {
1041 (*descriptor)[index] = pair.first[i];
1042 index += 2;
1043 }
1044 index += 2;
1045
1046 // wPropertyDataLength
1047 (*descriptor)[index++] = ((pair.second.size() + 1) * 2) & 0xFF;
1048 (*descriptor)[index++] =
1049 (((pair.second.size() + 1) * 2) >> UINT8_C(8)) & 0xFF;
1050 (*descriptor)[index++] =
1051 (((pair.second.size() + 1) * 2) >> UINT8_C(16)) & 0xFF;
1052 (*descriptor)[index++] =
1053 (((pair.second.size() + 1) * 2) >> UINT8_C(24)) & 0xFF;
1054
1055 // bPropertyData
1056 for (size_t i = 0; i < pair.second.size(); ++i) {
1057 (*descriptor)[index] = pair.second[i];
1058 index += 2;
1059 }
1060 index += 2;
1061 }
1062
1063 assert(index == length);
1064}
1065
Brian Silvermanf91524f2017-09-23 13:15:55 -04001066void UsbDevice::SetBdtEntry(int endpoint, Direction direction, EvenOdd odd,
1067 BdtEntry bdt_entry) {
1068 *MutableBdtEntry(endpoint, direction, odd) = bdt_entry;
1069}
1070
1071} // namespace teensy
1072} // namespace frc971