blob: e4a2b26239432c00d617f237042b980276ea0a58 [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
79__attribute__((aligned(512))) BdtEntry
80 usb0_buffer_descriptor_table[number_endpoints() * 2 /* rx/tx */ *
81 2 /* even/odd */];
82
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);
124 device_descriptor_->AddUint16(0x0200); // bcdUSB
125 device_descriptor_->AddByte(iad_device_class()); // bDeviceClass
126 device_descriptor_->AddByte(iad_device_subclass()); // bDeviceSubClass
127 device_descriptor_->AddByte(iad_device_protocol()); // bDeviceProtocol
128 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
214 config_descriptor_->AddByte(2 /* 4mA */); // bMaxPower
215
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:
443 for (UsbFunction *function : functions_) {
444 switch (function->HandleEndpoint0OutPacket(
445 bdt_entry->address, G_USB_BD_BC(bdt_entry->buffer_descriptor))) {
446 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.
476 //StallEndpoint0();
477 }
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) {
758 static uint8_t
759 kMicrosoftOsStringDescriptor
760 [] = {
761 0x12, // bLength
762 static_cast<uint8_t>(
763 UsbDescriptorType::kString), // bDescriptorType
764 0x4D,
765 0x00, 0x53, 0x00, 0x46, 0x00, 0x54, 0x00, 0x31,
766 0x00, 0x30, 0x00, 0x30,
767 0x00, // qwSignature
768 microsoft_vendor_code(), // bMS_VendorCode
769 0x00 // bPad
770 };
771 QueueEndpoint0Data(
772 reinterpret_cast<char *>(kMicrosoftOsStringDescriptor),
773 ::std::min<int>(setup_packet.length,
774 sizeof(kMicrosoftOsStringDescriptor)));
775 return;
776 }
Brian Silvermand930f282017-11-04 23:09:12 -0400777 if (descriptor_index != 0 &&
778 setup_packet.index != english_us_code()) {
Brian Silvermanf91524f2017-09-23 13:15:55 -0400779 break;
780 }
781 if (descriptor_index >= strings_.size()) {
782 break;
783 }
784 QueueEndpoint0Data(
785 strings_[descriptor_index].data(),
786 ::std::min<int>(setup_packet.length,
787 strings_[descriptor_index].size()));
788 return;
789
790 default:
791 // TODO(Brian): Handle other types of descriptor too.
792 break;
793 }
794 }
795 break;
796
Brian Silverman4aa83042018-01-05 12:47:31 -0800797 case SetupRequestType::kVendor:
798 switch (setup_packet.request) {
799 case microsoft_vendor_code():
800 if (!in) {
801 break;
802 }
803
804 switch (recipient) {
805 case standard_setup_recipients::kDevice:
806 if (setup_packet.value != 0) {
807 // Ignoring weird things and descriptors larger than 64K for
808 // now.
809 break;
810 }
811 switch (setup_packet.index) {
812 case microsoft_feature_descriptors::kExtendedCompatibilityId:
813 QueueEndpoint0Data(
814 microsoft_extended_id_descriptor_.data(),
815 ::std::min<int>(
816 setup_packet.length,
817 microsoft_extended_id_descriptor_.size()));
818 return;
819 }
820 break;
821
822 case standard_setup_recipients::kInterface:
823 switch (setup_packet.index) {
824 case microsoft_feature_descriptors::kExtendedProperties:
825 const int interface = setup_packet.value & 0xFF;
826 const int page_number = (setup_packet.value >> 8) & 0xFF;
827
828 if (page_number != 0) {
829 // Ignoring weird things and descriptors larger than 64K for
830 // now.
831 break;
832 }
833
834 const UsbFunction *const function =
835 interface_mapping_[interface];
836 const ::std::string &descriptor =
837 function->microsoft_extended_property_descriptor_;
838 if (descriptor.empty() ||
839 interface != function->first_interface_) {
840 break;
841 }
842 QueueEndpoint0Data(
843 descriptor.data(),
844 ::std::min<int>(setup_packet.length, descriptor.size()));
845 return;
846 }
847 break;
848 }
849 break;
850 }
851 break;
852
Brian Silvermanf91524f2017-09-23 13:15:55 -0400853 default:
854 for (UsbFunction *function : functions_) {
855 switch (function->HandleEndpoint0SetupPacket(setup_packet)) {
856 case SetupResponse::kIgnored:
857 continue;
858 case SetupResponse::kHandled:
859 return;
860 case SetupResponse::kStall:
861 break;
862 }
863 break;
864 }
865 break;
866 }
867
868 StallEndpoint0();
869}
870
871// We're supposed to continue returning stalls until the next kSetup packet.
872// Code might continue putting stuff in the TX buffers, but the hardware won't
873// actually send it as long as the EPSTALL bit is set.
874void UsbDevice::StallEndpoint0() {
875 USB0_ENDPT0 = USB_ENDPT_EPSTALL | USB_ENDPT_EPRXEN | USB_ENDPT_EPTXEN |
876 USB_ENDPT_EPHSHK;
877}
878
879bool UsbDevice::BufferEndpoint0TxPacket() {
880 if (endpoint0_data_ == nullptr) {
881 return false;
882 }
883
884 const int to_transmit = ::std::min(endpoint0_data_left_, kEndpoint0MaxSize);
885 BdtEntry *const tx_bdt_entry =
886 MutableBdtEntry(0, Direction::kTx, endpoint0_tx_odd_);
887 // const_cast is safe because the hardware is only going to read from
888 // this, not write.
889 tx_bdt_entry->address =
890 const_cast<void *>(static_cast<const void *>(endpoint0_data_));
891 dma_memory_barrier();
892 tx_bdt_entry->buffer_descriptor =
893 V_USB_BD_BC(to_transmit) | static_cast<uint32_t>(endpoint0_tx_toggle_) |
894 M_USB_BD_OWN | M_USB_BD_DTS;
895
896 endpoint0_tx_odd_ = EvenOddInverse(endpoint0_tx_odd_);
897 endpoint0_tx_toggle_ = Data01Inverse(endpoint0_tx_toggle_);
898
899 endpoint0_data_ += to_transmit;
900 endpoint0_data_left_ -= to_transmit;
901 if (to_transmit < kEndpoint0MaxSize) {
902 endpoint0_data_ = nullptr;
903 }
904
905 return true;
906}
907
908void UsbDevice::SendEmptyEndpoint0Packet() {
909 // Really doesn't matter what we put here as long as it's not nullptr.
910 endpoint0_data_ = reinterpret_cast<char *>(this);
911 endpoint0_data_left_ = 0;
912 BufferEndpoint0TxPacket();
913}
914
915void UsbDevice::QueueEndpoint0Data(const char *data, int size) {
916 endpoint0_data_ = data;
917 endpoint0_data_left_ = size;
918 // There are 2 TX buffers, so fill them both up.
919 BufferEndpoint0TxPacket();
920 BufferEndpoint0TxPacket();
921}
922
923void UsbDevice::StallEndpoint(int endpoint) {
924 for (Direction direction : {Direction::kTx, Direction::kRx}) {
925 for (EvenOdd odd : {EvenOdd::kOdd, EvenOdd::kEven}) {
926 MutableBdtEntry(endpoint, direction, odd)->buffer_descriptor = 0;
927 dma_memory_barrier();
928 MutableBdtEntry(endpoint, direction, odd)->address = nullptr;
929 }
930 }
931 USB0_ENDPTn(endpoint) |= USB_ENDPT_EPSTALL;
932}
933
934void UsbDevice::ConfigureEndpointFor(int endpoint, bool rx, bool tx,
935 bool handshake) {
936 uint8_t control = 0;
937 if (rx) {
938 control |= USB_ENDPT_EPRXEN;
939 }
940 if (tx) {
941 control |= USB_ENDPT_EPTXEN;
942 }
943 if (handshake) {
944 control |= USB_ENDPT_EPHSHK;
945 }
946 USB0_ENDPTn(endpoint) = control;
947}
948
949int UsbFunction::AddEndpoint() {
950 const int r = device_->endpoint_mapping_.size();
951 assert(r < number_endpoints());
952 device_->endpoint_mapping_.push_back(this);
953 return r;
954}
955
956int UsbFunction::AddInterface() {
957 const int r = device_->interface_mapping_.size();
958 // bInterfaceNumber is only one byte.
959 assert(r < 255);
960 device_->interface_mapping_.push_back(this);
961 return r;
962}
963
Brian Silverman4aa83042018-01-05 12:47:31 -0800964void UsbFunction::CreateIadDescriptor(int first_interface, int interface_count,
965 int function_class, int function_subclass,
966 int function_protocol,
967 const ::std::string &function) {
968 first_interface_ = first_interface;
969 const auto iad_descriptor = CreateDescriptor(
970 iad_descriptor_length(), UsbDescriptorType::kInterfaceAssociation);
971 iad_descriptor->AddByte(first_interface); // bFirstInterface
972 iad_descriptor->AddByte(interface_count); // bInterfaceCount
973 iad_descriptor->AddByte(function_class); // bFunctionClass
974 iad_descriptor->AddByte(function_subclass); // bFunctionSubClass
975 iad_descriptor->AddByte(function_protocol); // bFunctionProtocol
976 iad_descriptor->AddByte(device()->AddString(function)); // iFunction
977}
978
979void UsbFunction::SetMicrosoftDeviceInterfaceGuids(const ::std::string &guids) {
980 ::std::map<::std::string, ::std::string> properties;
981 properties["DeviceInterfaceGUIDs"] = guids + ::std::string(1, '\0');
982 ::std::string *const descriptor = &microsoft_extended_property_descriptor_;
983
984 uint32_t length = 10;
985 for (auto &pair : properties) {
986 length += 14;
987 length += (pair.first.size() + 1) * 2;
988 length += (pair.second.size() + 1) * 2;
989 }
990 descriptor->resize(length);
991 int index = 0;
992
993 // dwLength
994 (*descriptor)[index++] = length & 0xFF;
995 (*descriptor)[index++] = (length >> UINT32_C(8)) & 0xFF;
996 (*descriptor)[index++] = (length >> UINT32_C(16)) & 0xFF;
997 (*descriptor)[index++] = (length >> UINT32_C(24)) & 0xFF;
998
999 // bcdVersion
1000 (*descriptor)[index++] = 0x00;
1001 (*descriptor)[index++] = 0x01;
1002
1003 // wIndex
1004 (*descriptor)[index++] = microsoft_feature_descriptors::kExtendedProperties;
1005 (*descriptor)[index++] = 0;
1006
1007 // wCount
1008 (*descriptor)[index++] = properties.size() & 0xFF;
1009 (*descriptor)[index++] = (properties.size() >> 8) & 0xFF;
1010
1011 for (auto &pair : properties) {
1012 const uint32_t size = 14 + (pair.first.size() + pair.second.size() + 2) * 2;
1013 // dwSize
1014 (*descriptor)[index++] = size & 0xFF;
1015 (*descriptor)[index++] = (size >> UINT32_C(8)) & 0xFF;
1016 (*descriptor)[index++] = (size >> UINT32_C(16)) & 0xFF;
1017 (*descriptor)[index++] = (size >> UINT32_C(24)) & 0xFF;
1018
1019 // Need to get this from the map if we ever do others in the future.
1020 const uint32_t data_type = 7; // REG_MULTI_SZ
1021 // dwPropertyDataType
1022 (*descriptor)[index++] = data_type & 0xFF;
1023 (*descriptor)[index++] = (data_type >> UINT32_C(8)) & 0xFF;
1024 (*descriptor)[index++] = (data_type >> UINT32_C(16)) & 0xFF;
1025 (*descriptor)[index++] = (data_type >> UINT32_C(24)) & 0xFF;
1026
1027 // wPropertyNameLength
1028 (*descriptor)[index++] = ((pair.first.size() + 1) * 2) & 0xFF;
1029 (*descriptor)[index++] = (((pair.first.size() + 1) * 2) >> 8) & 0xFF;
1030
1031 // bPropertyName
1032 for (size_t i = 0; i < pair.first.size(); ++i) {
1033 (*descriptor)[index] = pair.first[i];
1034 index += 2;
1035 }
1036 index += 2;
1037
1038 // wPropertyDataLength
1039 (*descriptor)[index++] = ((pair.second.size() + 1) * 2) & 0xFF;
1040 (*descriptor)[index++] =
1041 (((pair.second.size() + 1) * 2) >> UINT8_C(8)) & 0xFF;
1042 (*descriptor)[index++] =
1043 (((pair.second.size() + 1) * 2) >> UINT8_C(16)) & 0xFF;
1044 (*descriptor)[index++] =
1045 (((pair.second.size() + 1) * 2) >> UINT8_C(24)) & 0xFF;
1046
1047 // bPropertyData
1048 for (size_t i = 0; i < pair.second.size(); ++i) {
1049 (*descriptor)[index] = pair.second[i];
1050 index += 2;
1051 }
1052 index += 2;
1053 }
1054
1055 assert(index == length);
1056}
1057
Brian Silvermanf91524f2017-09-23 13:15:55 -04001058void UsbDevice::SetBdtEntry(int endpoint, Direction direction, EvenOdd odd,
1059 BdtEntry bdt_entry) {
1060 *MutableBdtEntry(endpoint, direction, odd) = bdt_entry;
1061}
1062
1063} // namespace teensy
1064} // namespace frc971