blob: 306769523a45f17001bf016536775d67fe189b5c [file] [log] [blame]
Brian Silvermanf91524f2017-09-23 13:15:55 -04001#include "motors/usb/usb.h"
2
3#include <string.h>
4
5#include "motors/util.h"
6
7namespace frc971 {
8namespace teensy {
9namespace {
10
11// The mask of interrupts we care about.
12constexpr uint32_t usb_enabled_interrupts() {
13 // Deliberately not turning the sleep interrupt on here because we just
14 // want to ignore that anyways.
15 return USB_INTEN_TOKDNEEN | USB_INTEN_SOFTOKEN | USB_INTEN_ERROREN |
16 USB_INTEN_USBRSTEN;
17}
18
19// The names of all the standard setup requests which come in on endpoint 0.
20namespace standard_setup_requests {
21constexpr int kGetStatus = 0;
22constexpr int kClearFeature = 1;
23constexpr int kSetFeature = 3;
24constexpr int kSetAddress = 5;
25constexpr int kGetDescriptor = 6;
26constexpr int kSetDescriptor = 7;
27constexpr int kGetConfiguration = 8;
28constexpr int kSetConfiguration = 9;
29constexpr int kGetInterface = 10;
30constexpr int kSetInterface = 11;
31constexpr int kSynchFrame = 12;
32} // namespace standard_setup_requests
33
34// The names of the standard feature selectors.
35namespace standard_feature_selectors {
36constexpr int kDeviceRemoteWakeup = 1;
37constexpr int kEndpointHalt = 0;
38constexpr int kTestMode = 2;
39} // namespace standard_feature_selectors
40
41// The names of all the PIDs (Packet IDs) from the USB standard. Note that this
42// USB hardware doesn't expose most of them, especially in device mode.
43enum class UsbPid {
44 kOut = 0x1,
45 kIn = 0x9,
46 kSof = 0x5,
47 kSetup = 0xD,
48 kData0 = 0x3,
49 kData1 = 0xB,
50 kData2 = 0x7,
51 kMData = 0xF,
52 kAck = 0x2,
53 kNak = 0xA,
54 kStall = 0xE,
55 kNYet = 0x6,
56 kPre = 0xC,
57 kErr = 0xC,
58 kSplit = 0x8,
59 kPing = 0x4,
60 kReserved = 0x0,
61};
62
63// The device class for using IADs.
64constexpr uint8_t iad_device_class() { return 0xEF; }
65// The device subclass for using IADs.
66constexpr uint8_t iad_device_subclass() { return 0x02; }
67// The device protocol for using IADs.
68constexpr uint8_t iad_device_protocol() { return 0x01; }
69
70// The total number of endpoints supported by this hardware.
71constexpr int number_endpoints() { return 16; }
72
73__attribute__((aligned(512))) BdtEntry
74 usb0_buffer_descriptor_table[number_endpoints() * 2 /* rx/tx */ *
75 2 /* even/odd */];
76
77// Returns the specified BDT entry.
78BdtEntry *MutableBdtEntry(int endpoint, Direction direction, EvenOdd odd) {
79 return &usb0_buffer_descriptor_table[static_cast<uint32_t>(endpoint << 2) |
80 static_cast<uint32_t>(direction) |
81 static_cast<uint32_t>(odd)];
82}
83
84// Returns the BDT entry corresponding to a USBx_STAT value.
85BdtEntry *MutableBdtEntryFromStat(uint8_t stat) {
86 return &usb0_buffer_descriptor_table[static_cast<uint32_t>(stat) >> 2];
87}
88
89// A pointer to the object we're going to ask to handle interrupts.
90UsbDevice *volatile global_usb0_device = nullptr;
91
92} // namespace
93
94UsbDevice::UsbDevice(int index, uint16_t vendor_id, uint16_t product_id)
95 : index_(index) {
96 // TODO(Brian): Pass index_ into all the register access macros. Also sort out
97 // how to deal with it for the interrupts.
98 assert(index == 0);
99
100 assert(global_usb0_device == nullptr);
101 global_usb0_device = this;
102
103 // Endpoint 0 isn't a normal endpoint, so it doesn't show up in here.
104 endpoint_mapping_.push_back(nullptr);
105
106 // Set up the "String Descriptor Zero, Specifying Languages Supported by the
107 // Device" (aka english_us_code() only).
108 strings_.emplace_back(4, '\0');
109 strings_.back()[0] = 4;
110 strings_.back()[1] = static_cast<uint8_t>(UsbDescriptorType::kString);
111 strings_.back()[2] = english_us_code() & 0xFF;
112 strings_.back()[3] = (english_us_code() >> 8) & 0xFF;
113
114 device_descriptor_ =
115 device_descriptor_list_.CreateDescriptor(18, UsbDescriptorType::kDevice);
116 device_descriptor_->AddUint16(0x0200); // bcdUSB
117 device_descriptor_->AddByte(iad_device_class()); // bDeviceClass
118 device_descriptor_->AddByte(iad_device_subclass()); // bDeviceSubClass
119 device_descriptor_->AddByte(iad_device_protocol()); // bDeviceProtocol
120 device_descriptor_->AddByte(kEndpoint0MaxSize); // bMaxPacketSize0
121 device_descriptor_->AddUint16(vendor_id); // idVendor
122 device_descriptor_->AddUint16(product_id); // idProduct
123 device_descriptor_->AddUint16(0); // bcdDevice
124 // We might overwrite these string descriptor indices later if we get strings
125 // to put there.
126 device_descriptor_->AddByte(0); // iManufacturer
127 device_descriptor_->AddByte(0); // iProduct
128 device_descriptor_->AddByte(0); // iSerialNumber
129 device_descriptor_->AddByte(1); // bNumConfigurations
130
131 config_descriptor_ = config_descriptor_list_.CreateDescriptor(
132 9, UsbDescriptorType::kConfiguration);
133}
134
135UsbDevice::~UsbDevice() {
136 NVIC_DISABLE_IRQ(IRQ_USBOTG);
137 dma_memory_barrier();
138 assert(global_usb0_device == this);
139 global_usb0_device = nullptr;
140}
141
142void UsbDevice::Initialize() {
143 assert(!is_set_up_);
144
145 for (UsbFunction *function : functions_) {
146 function->Initialize();
147 }
148
149 config_descriptor_->AddUint16(
150 config_descriptor_list_.CurrentSize()); // wTotalLength
151 config_descriptor_->AddByte(interface_mapping_.size()); // bNumInterfaces
152 config_descriptor_->AddByte(1); // bConfigurationValue
153 // Doesn't seem to be much point naming our one and only configuration.
154 config_descriptor_->AddByte(0); // iConfiguration
155 config_descriptor_->AddByte((1 << 7) /* Reserved */ |
156 (1 << 6) /* Self-powered */); // bmAttribute
157 config_descriptor_->AddByte(2 /* 4mA */); // bMaxPower
158
159 device_descriptor_.reset();
160 config_descriptor_.reset();
161 device_descriptor_list_.CheckFinished();
162 config_descriptor_list_.CheckFinished();
163 is_set_up_ = true;
164
165 // Make sure all the buffer descriptors are clear.
166 for (int i = 0; i < number_endpoints(); ++i) {
167 for (Direction direction : {Direction::kTx, Direction::kRx}) {
168 for (EvenOdd odd : {EvenOdd::kOdd, EvenOdd::kEven}) {
169 MutableBdtEntry(i, direction, odd)->buffer_descriptor = 0;
170 MutableBdtEntry(i, direction, odd)->address = nullptr;
171 }
172 }
173 }
174 dma_memory_barrier();
175
176 // The other startup code handles getting the incoming 48MHz clock running.
177 SIM_SCGC4 |= SIM_SCGC4_USBOTG;
178 MPU_RGDAAC0 |= 0x03000000;
179
180 // Reset it.
181 USB0_USBTRC0 = USB_USBTRC_USBRESET;
182 // TRM says to wait "two USB clock cycles", so assume that's at 48MHz and then
183 // round up, being pessimistic in assuming each read from the peripheral is
184 // only a single core clock. This wildly overapproximates how long we need to
185 // wait, but whatever.
186 for (int i = 0; i < ((F_CPU / 48000000) + 1) * 2; ++i) {
187 while ((USB0_USBTRC0 & USB_USBTRC_USBRESET) != 0) {
188 }
189 }
190
191 USB0_BDTPAGE1 =
192 reinterpret_cast<uintptr_t>(&usb0_buffer_descriptor_table[0]) >> 8;
193 USB0_BDTPAGE2 =
194 reinterpret_cast<uintptr_t>(&usb0_buffer_descriptor_table[0]) >> 16;
195 USB0_BDTPAGE3 =
196 reinterpret_cast<uintptr_t>(&usb0_buffer_descriptor_table[0]) >> 24;
197
198 // The Quick Reference User Guide says to clear all the interrupts.
199 ClearInterrupts();
200 USB0_OTGISTAT = USB_OTGISTAT_ONEMSEC | USB_OTGISTAT_LINE_STATE_CHG;
201
202 // Now enable the module.
203 USB0_CTL = USB_CTL_USBENSOFEN;
204
205 // Un-suspend the transceiver and disable weak pulldowns.
206 USB0_USBCTRL = 0;
207 // And enable the D+ pullup which indicates we're a full-speed device.
208 USB0_CONTROL = USB_CONTROL_DPPULLUPNONOTG;
209
210 // Enable the reset interrupt (which is the first one we care about).
211 USB0_INTEN = USB_INTEN_USBRSTEN;
212
213 dma_memory_barrier();
214 NVIC_ENABLE_IRQ(IRQ_USBOTG);
215}
216
217void usb_isr(void) {
218 UsbDevice *const usb0_device = global_usb0_device;
219 if (usb0_device == nullptr) {
220 NVIC_DISABLE_IRQ(IRQ_USBOTG);
221 } else {
222 usb0_device->HandleInterrupt();
223 }
224}
225
226void UsbDevice::ClearInterrupts() {
227 USB0_ISTAT = USB_ISTAT_ATTACH | USB_ISTAT_RESUME | USB_ISTAT_SLEEP |
228 USB_ISTAT_TOKDNE | USB_ISTAT_SOFTOK | USB_ISTAT_ERROR |
229 USB_ISTAT_USBRST;
230 USB0_ERRSTAT = USB_ERRSTAT_BTSERR | USB_ERRSTAT_DMAERR | USB_ERRSTAT_BTOERR |
231 USB_ERRSTAT_DFN8 | USB_ERRSTAT_CRC16 | USB_ERRSTAT_CRC5EOF |
232 USB_ERRSTAT_PIDERR;
233}
234
235void UsbDevice::HandleInterrupt() {
236 while (true) {
237 const uint32_t status = USB0_ISTAT;
238 if ((status & usb_enabled_interrupts()) == 0) {
239 return;
240 }
241
242 // If we just got a start-of-frame token, then ask all the functions what to
243 // do.
244 if (status & USB_ISTAT_SOFTOK) {
245 // TODO(Brian): Actually ask the functions, maybe only if we're
246 // configured.
247 USB0_ISTAT = USB_ISTAT_SOFTOK;
248 }
249
250 // If we just finished processing a token.
251 if (status & USB_ISTAT_TOKDNE) {
252 const uint8_t stat = USB0_STAT;
253 const int endpoint = G_USB_STAT_ENDP(stat);
254
255 if (endpoint == 0) {
256 HandleEndpoint0Token(stat);
257 } else {
258 BdtEntry *const bdt_entry = MutableBdtEntryFromStat(stat);
259 const UsbPid pid = G_USB_BD_PID(bdt_entry->buffer_descriptor);
260 UsbFunction *const function = endpoint_mapping_[endpoint];
261 if (function == nullptr) {
262 // Should never happen, so stall if we do get here somehow.
263 StallEndpoint(endpoint);
264 } else {
265 switch (pid) {
266 case UsbPid::kOut:
267 function->HandleOutFinished(endpoint, bdt_entry);
268 break;
269
270 case UsbPid::kIn:
271 function->HandleInFinished(
272 endpoint, bdt_entry,
273 (stat & M_USB_STAT_ODD) ? EvenOdd::kOdd : EvenOdd::kEven);
274 break;
275
276 case UsbPid::kSetup:
277 default:
278 // Should never happen, so stall if we do get here somehow.
279 StallEndpoint(endpoint);
280 break;
281 }
282 }
283 }
284
285 USB0_ISTAT = USB_ISTAT_TOKDNE;
286 }
287
288 if (status & USB_ISTAT_USBRST) {
289 // Use DATA0 for all endpoints.
290 USB0_CTL = USB_CTL_ODDRST;
291 endpoint0_tx_odd_ = EvenOdd::kEven;
292 endpoint0_tx_toggle_ = Data01::kData0;
293
294 for (UsbFunction *function : functions_) {
295 function->HandleReset();
296 }
297
298 MutableBdtEntry(0, Direction::kRx, EvenOdd::kEven)->buffer_descriptor =
299 M_USB_BD_OWN | M_USB_BD_DTS | V_USB_BD_BC(kEndpoint0MaxSize);
300 MutableBdtEntry(0, Direction::kRx, EvenOdd::kEven)->address =
301 &endpoint0_receive_buffer_[0][0];
302
303 MutableBdtEntry(0, Direction::kRx, EvenOdd::kOdd)->buffer_descriptor =
304 M_USB_BD_OWN | M_USB_BD_DTS | V_USB_BD_BC(kEndpoint0MaxSize);
305 MutableBdtEntry(0, Direction::kRx, EvenOdd::kOdd)->address =
306 &endpoint0_receive_buffer_[1][0];
307
308 MutableBdtEntry(0, Direction::kTx, EvenOdd::kEven)->buffer_descriptor = 0;
309 MutableBdtEntry(0, Direction::kTx, EvenOdd::kOdd)->buffer_descriptor = 0;
310
311 USB0_ENDPT0 = USB_ENDPT_EPRXEN | USB_ENDPT_EPTXEN | USB_ENDPT_EPHSHK;
312
313 ClearInterrupts();
314
315 // Set the address to 0 for enumeration.
316 USB0_ADDR = 0;
317 new_address_ = 0;
318
319 endpoint0_data_ = nullptr;
320 endpoint0_data_left_ = 0;
321
322 USB0_INTEN = usb_enabled_interrupts();
323 USB0_ERREN = USB_ERREN_BTSERREN | USB_ERREN_DMAERREN |
324 USB_ERREN_BTOERREN | USB_ERREN_DFN8EN | USB_ERREN_CRC16EN |
325 USB_ERREN_CRC5EOFEN | USB_ERREN_PIDERREN;
326
327 // Start the peripheral going.
328 dma_memory_barrier();
329 USB0_CTL = USB_CTL_USBENSOFEN;
330
331 continue;
332 }
333
334 // TODO(Brian): Handle errors more intelligently.
335 if (status & USB_ISTAT_ERROR) {
336 const uint8_t error = USB0_ERRSTAT;
337 USB0_ERRSTAT = error;
338 USB0_ISTAT = USB_ISTAT_ERROR;
339 }
340 }
341}
342
343void UsbDevice::HandleEndpoint0Token(const uint8_t stat) {
344 BdtEntry *const bdt_entry = MutableBdtEntryFromStat(stat);
345 const UsbPid pid = G_USB_BD_PID(bdt_entry->buffer_descriptor);
346 switch (pid) {
347 case UsbPid::kSetup:
348 // Unstall it if it was previously stalled.
349 USB0_ENDPT0 = USB_ENDPT_EPRXEN | USB_ENDPT_EPTXEN | USB_ENDPT_EPHSHK;
350
351 SetupPacket setup_packet;
352 memcpy(&setup_packet, bdt_entry->address, sizeof(setup_packet));
353
354 // Give the buffer back now.
355 dma_memory_barrier();
356 // Next IN and OUT packet for this endpoint (data stage/status stage)
357 // should both be DATA1.
358 // TODO(Brian): Does this actually deal with received toggles correctly?
359 bdt_entry->buffer_descriptor =
360 M_USB_BD_OWN | M_USB_BD_DTS | V_USB_BD_BC(kEndpoint0MaxSize);
361 MutableBdtEntryFromStat(stat ^ M_USB_STAT_ODD)->buffer_descriptor =
362 M_USB_BD_OWN | M_USB_BD_DTS | V_USB_BD_BC(kEndpoint0MaxSize) |
363 M_USB_BD_DATA1;
364 endpoint0_tx_toggle_ = Data01::kData1;
365
366 // TODO(Brian): Tell the functions a new setup packet is starting.
367 // CdcTty: next_endpoint0_out_ = NextEndpoint0Out::kNone;
368
369 // Forget about any pending transactions on this endpoint. There shouldn't
370 // be any, so if we think there are something's out of sync and we should
371 // just drop it. Important to do this before clearing TXD_SUSPEND in
372 // USBx_CTL. Standard says "If a Setup transaction is received by an
373 // endpoint before a previously initiated control transfer is completed,
374 // the device must abort the current transfer/operation".
375 endpoint0_data_ = nullptr;
376 endpoint0_data_left_ = 0;
377 MutableBdtEntry(0, Direction::kTx, EvenOdd::kEven)->buffer_descriptor = 0;
378 MutableBdtEntry(0, Direction::kTx, EvenOdd::kOdd)->buffer_descriptor = 0;
379
380 HandleEndpoint0SetupPacket(setup_packet);
381
382 break;
383
384 case UsbPid::kOut:
385 for (UsbFunction *function : functions_) {
386 switch (function->HandleEndpoint0OutPacket(
387 bdt_entry->address, G_USB_BD_BC(bdt_entry->buffer_descriptor))) {
388 case SetupResponse::kIgnored:
389 break;
390 case SetupResponse::kHandled:
391 dma_memory_barrier();
392 bdt_entry->buffer_descriptor =
393 M_USB_BD_OWN | M_USB_BD_DTS | V_USB_BD_BC(kEndpoint0MaxSize);
394 return;
395 case SetupResponse::kStall:
396 bdt_entry->buffer_descriptor =
397 M_USB_BD_OWN | M_USB_BD_DTS | V_USB_BD_BC(kEndpoint0MaxSize);
398 StallEndpoint0();
399 return;
400 }
401 }
402 bdt_entry->buffer_descriptor =
403 M_USB_BD_OWN | M_USB_BD_DTS | V_USB_BD_BC(kEndpoint0MaxSize);
404 StallEndpoint0();
405 return;
406
407 case UsbPid::kIn:
408 // The functions are allowed to queue data in {endpoint0_data_,
409 // endpoint0_data_left_}, so this case deals with sending their data too.
410
411 // An IN transaction completed, so set up for the next one if appropriate.
412 if (!BufferEndpoint0TxPacket()) {
413 // After we're done, any further requests from the host should result in
414 // stalls (until the next setup token).
415 // TODO(Brian): Keep track of which direction it is and how much we've
416 // finished so we actually know when to stall it, both here and for
417 // kOut tokens.
418 //StallEndpoint0();
419 }
420
421 // If we have a new address, there is nothing left in the setup request
422 // besides a single IN packet forming the status stage, so we know the
423 // changes must be done now.
424 if (new_address_ != 0) {
425 USB0_ADDR = new_address_;
426 new_address_ = 0;
427 }
428
429 break;
430
431 default:
432 // Should never happen, but give the buffer back anyways if necessary.
433 if (!(bdt_entry->buffer_descriptor & M_USB_BD_OWN)) {
434 bdt_entry->buffer_descriptor =
435 M_USB_BD_OWN | M_USB_BD_DTS | V_USB_BD_BC(kEndpoint0MaxSize);
436 }
437 break;
438 }
439
440 // Clear the TXD_SUSPEND flag.
441 dma_memory_barrier();
442 USB0_CTL = USB_CTL_USBENSOFEN;
443}
444
445void UsbDevice::HandleEndpoint0SetupPacket(const SetupPacket &setup_packet) {
446 const bool in = setup_packet.request_type & M_SETUP_REQUEST_TYPE_IN;
447 const uint8_t recipient =
448 G_SETUP_REQUEST_TYPE_RECIPIENT(setup_packet.request_type);
449 switch (G_SETUP_REQUEST_TYPE_TYPE(setup_packet.request_type)) {
450 case SetupRequestType::kStandard:
451 switch (setup_packet.request) {
452 case standard_setup_requests::kSetAddress:
453 if (in || recipient != standard_setup_recipients::kDevice ||
454 setup_packet.index != 0 || setup_packet.length != 0) {
455 break;
456 }
457 new_address_ = setup_packet.value;
458 SendEmptyEndpoint0Packet();
459 return;
460
461 case standard_setup_requests::kSetConfiguration:
462 if (in || recipient != standard_setup_recipients::kDevice ||
463 setup_packet.index != 0 || setup_packet.length != 0) {
464 break;
465 }
466 configuration_ = setup_packet.value;
467
468 // No need to mess with endpoint0_tx_toggle_ because we reset it with
469 // each setup packet anyways.
470
471 for (int endpoint = 0;
472 endpoint < static_cast<int>(endpoint_mapping_.size());
473 ++endpoint) {
474 if (endpoint_mapping_[endpoint]) {
475 endpoint_mapping_[endpoint]->HandleConfigured(endpoint);
476 }
477 }
478
479 SendEmptyEndpoint0Packet();
480 return;
481
482 case standard_setup_requests::kClearFeature:
483 if (in || setup_packet.length != 0) {
484 break;
485 }
486 if (recipient == standard_setup_recipients::kEndpoint &&
487 setup_packet.value == standard_feature_selectors::kEndpointHalt) {
488 const int endpoint =
489 G_SETUP_REQUEST_INDEX_ENDPOINT(setup_packet.index);
490 // Our endpoint 0 doesn't support the halt feature because that's
491 // weird and not recommended by the standard.
492 if (endpoint == 0) {
493 break;
494 }
495 if (endpoint >= number_endpoints()) {
496 break;
497 }
498 USB0_ENDPTn(endpoint) &= ~USB_ENDPT_EPSTALL;
499 if (endpoint_mapping_[endpoint] != nullptr) {
500 endpoint_mapping_[endpoint]->HandleConfigured(endpoint);
501 }
502 SendEmptyEndpoint0Packet();
503 return;
504 }
505 // We should never get kDeviceRemoteWakeup because we don't advertise
506 // support for it in our configuration descriptors.
507 // We should never get kTestMode because we're not high-speed.
508 break;
509
510 case standard_setup_requests::kSetFeature:
511 if (in || setup_packet.length != 0) {
512 break;
513 }
514 if (recipient == standard_setup_recipients::kEndpoint &&
515 setup_packet.value == standard_feature_selectors::kEndpointHalt) {
516 const int endpoint =
517 G_SETUP_REQUEST_INDEX_ENDPOINT(setup_packet.index);
518 // Our endpoint 0 doesn't support the halt feature because that's
519 // weird and not recommended by the standard.
520 if (endpoint == 0) {
521 break;
522 }
523 if (endpoint >= number_endpoints()) {
524 break;
525 }
526 StallEndpoint(endpoint);
527 // TODO(Brian): Tell the appropriate function it's now stalled.
528 SendEmptyEndpoint0Packet();
529 return;
530 }
531 // We should never get kDeviceRemoteWakeup because we don't advertise
532 // support for it in our configuration descriptors.
533 // We should never get kTestMode because we're not high-speed.
534 break;
535
536 case standard_setup_requests::kGetConfiguration:
537 if (!in || recipient != standard_setup_recipients::kDevice ||
538 setup_packet.index != 0 || setup_packet.length != 1) {
539 break;
540 }
541 endpoint0_transmit_buffer_[0] = configuration_;
542 QueueEndpoint0Data(endpoint0_transmit_buffer_, 1);
543 return;
544
545 case standard_setup_requests::kGetInterface:
546 if (!in || recipient != standard_setup_recipients::kInterface ||
547 setup_packet.value != 0 || setup_packet.length != 1) {
548 break;
549 }
550 // Standard says it's unspecified in the default state and must
551 // respond with an error in the address state, so just do an error for
552 // both of them.
553 if (configuration_ == 0) {
554 break;
555 }
556 // TODO(Brian): Ask the appropriate function what alternate setting
557 // the interface has, and stall if there isn't one.
558 endpoint0_transmit_buffer_[0] = 0;
559 QueueEndpoint0Data(endpoint0_transmit_buffer_, 1);
560 return;
561
562 case standard_setup_requests::kSetInterface:
563 if (in || recipient != standard_setup_recipients::kInterface ||
564 setup_packet.length != 0) {
565 break;
566 }
567 // Standard says it's unspecified in the default state and must
568 // respond with an error in the address state, so just do an error for
569 // both of them.
570 if (configuration_ == 0) {
571 break;
572 }
573
574 // TODO(Brian): Pass to the appropriate function instead.
575 if (setup_packet.value != 0) {
576 break;
577 }
578 SendEmptyEndpoint0Packet();
579 return;
580
581 case standard_setup_requests::kGetStatus:
582 if (!in || setup_packet.value != 0 || setup_packet.length != 2) {
583 break;
584 }
585 if (recipient == standard_setup_recipients::kDevice) {
586 if (setup_packet.index != 0) {
587 break;
588 }
589 // Say that we're currently self powered.
590 endpoint0_transmit_buffer_[0] = 1;
591 endpoint0_transmit_buffer_[1] = 0;
592 QueueEndpoint0Data(endpoint0_transmit_buffer_, 2);
593 return;
594 }
595 if ((recipient == standard_setup_recipients::kInterface &&
596 setup_packet.index == 0) ||
597 (recipient == standard_setup_recipients::kEndpoint &&
598 G_SETUP_REQUEST_INDEX_ENDPOINT(setup_packet.index) == 0)) {
599 endpoint0_transmit_buffer_[0] = 0;
600 endpoint0_transmit_buffer_[1] = 0;
601 QueueEndpoint0Data(endpoint0_transmit_buffer_, 2);
602 return;
603 }
604 // Standard says it's unspecified in the default state and must
605 // respond with an error in the address state, so just do an error
606 // for both of them.
607 if (configuration_ == 0) {
608 break;
609 }
610
611 if (recipient == standard_setup_recipients::kInterface) {
612 // TODO(Brian): Check if it's actually an interface we have?
613 endpoint0_transmit_buffer_[0] = 0;
614 endpoint0_transmit_buffer_[1] = 0;
615 QueueEndpoint0Data(endpoint0_transmit_buffer_, 2);
616 return;
617 }
618
619 if (recipient == standard_setup_recipients::kEndpoint) {
620 const int endpoint =
621 G_SETUP_REQUEST_INDEX_ENDPOINT(setup_packet.index);
622 // TODO(Brian): Check if it's actually an endpoint we have?
623 if (USB0_ENDPTn(endpoint) & USB_ENDPT_EPSTALL) {
624 endpoint0_transmit_buffer_[0] = 1;
625 } else {
626 endpoint0_transmit_buffer_[0] = 0;
627 }
628 endpoint0_transmit_buffer_[1] = 0;
629 QueueEndpoint0Data(endpoint0_transmit_buffer_, 2);
630 return;
631 }
632 break;
633
634 case standard_setup_requests::kSetDescriptor:
635 // Not implementing anything for this.
636 break;
637
638 case standard_setup_requests::kSynchFrame:
639 // We don't implement any classes which use this.
640 break;
641
642 case standard_setup_requests::kGetDescriptor:
643 if (!in || recipient != standard_setup_recipients::kDevice) {
644 break;
645 }
646 const uint8_t descriptor_type_byte = (setup_packet.value >> 8) & 0xFF;
647 if (descriptor_type_byte < kUsbDescriptorTypeMin ||
648 descriptor_type_byte > kUsbDescriptorTypeMax) {
649 break;
650 }
651 const UsbDescriptorType descriptor_type =
652 static_cast<UsbDescriptorType>(descriptor_type_byte);
653 const uint8_t descriptor_index = setup_packet.value & 0xFF;
654 switch (descriptor_type) {
655 case UsbDescriptorType::kDevice:
656 if (setup_packet.index != 0 || descriptor_index != 0) {
657 break;
658 }
659 QueueEndpoint0Data(
660 device_descriptor_list_.data_.data(),
661 ::std::min<int>(setup_packet.length,
662 device_descriptor_list_.data_.size()));
663 return;
664
665 case UsbDescriptorType::kConfiguration:
666 if (setup_packet.index != 0 || descriptor_index != 0) {
667 break;
668 }
669 QueueEndpoint0Data(
670 config_descriptor_list_.data_.data(),
671 ::std::min<int>(setup_packet.length,
672 config_descriptor_list_.data_.size()));
673 return;
674
675 case UsbDescriptorType::kString:
676 if (descriptor_index != 0 && setup_packet.index != english_us_code()) {
677 break;
678 }
679 if (descriptor_index >= strings_.size()) {
680 break;
681 }
682 QueueEndpoint0Data(
683 strings_[descriptor_index].data(),
684 ::std::min<int>(setup_packet.length,
685 strings_[descriptor_index].size()));
686 return;
687
688 default:
689 // TODO(Brian): Handle other types of descriptor too.
690 break;
691 }
692 }
693 break;
694
695 default:
696 for (UsbFunction *function : functions_) {
697 switch (function->HandleEndpoint0SetupPacket(setup_packet)) {
698 case SetupResponse::kIgnored:
699 continue;
700 case SetupResponse::kHandled:
701 return;
702 case SetupResponse::kStall:
703 break;
704 }
705 break;
706 }
707 break;
708 }
709
710 StallEndpoint0();
711}
712
713// We're supposed to continue returning stalls until the next kSetup packet.
714// Code might continue putting stuff in the TX buffers, but the hardware won't
715// actually send it as long as the EPSTALL bit is set.
716void UsbDevice::StallEndpoint0() {
717 USB0_ENDPT0 = USB_ENDPT_EPSTALL | USB_ENDPT_EPRXEN | USB_ENDPT_EPTXEN |
718 USB_ENDPT_EPHSHK;
719}
720
721bool UsbDevice::BufferEndpoint0TxPacket() {
722 if (endpoint0_data_ == nullptr) {
723 return false;
724 }
725
726 const int to_transmit = ::std::min(endpoint0_data_left_, kEndpoint0MaxSize);
727 BdtEntry *const tx_bdt_entry =
728 MutableBdtEntry(0, Direction::kTx, endpoint0_tx_odd_);
729 // const_cast is safe because the hardware is only going to read from
730 // this, not write.
731 tx_bdt_entry->address =
732 const_cast<void *>(static_cast<const void *>(endpoint0_data_));
733 dma_memory_barrier();
734 tx_bdt_entry->buffer_descriptor =
735 V_USB_BD_BC(to_transmit) | static_cast<uint32_t>(endpoint0_tx_toggle_) |
736 M_USB_BD_OWN | M_USB_BD_DTS;
737
738 endpoint0_tx_odd_ = EvenOddInverse(endpoint0_tx_odd_);
739 endpoint0_tx_toggle_ = Data01Inverse(endpoint0_tx_toggle_);
740
741 endpoint0_data_ += to_transmit;
742 endpoint0_data_left_ -= to_transmit;
743 if (to_transmit < kEndpoint0MaxSize) {
744 endpoint0_data_ = nullptr;
745 }
746
747 return true;
748}
749
750void UsbDevice::SendEmptyEndpoint0Packet() {
751 // Really doesn't matter what we put here as long as it's not nullptr.
752 endpoint0_data_ = reinterpret_cast<char *>(this);
753 endpoint0_data_left_ = 0;
754 BufferEndpoint0TxPacket();
755}
756
757void UsbDevice::QueueEndpoint0Data(const char *data, int size) {
758 endpoint0_data_ = data;
759 endpoint0_data_left_ = size;
760 // There are 2 TX buffers, so fill them both up.
761 BufferEndpoint0TxPacket();
762 BufferEndpoint0TxPacket();
763}
764
765void UsbDevice::StallEndpoint(int endpoint) {
766 for (Direction direction : {Direction::kTx, Direction::kRx}) {
767 for (EvenOdd odd : {EvenOdd::kOdd, EvenOdd::kEven}) {
768 MutableBdtEntry(endpoint, direction, odd)->buffer_descriptor = 0;
769 dma_memory_barrier();
770 MutableBdtEntry(endpoint, direction, odd)->address = nullptr;
771 }
772 }
773 USB0_ENDPTn(endpoint) |= USB_ENDPT_EPSTALL;
774}
775
776void UsbDevice::ConfigureEndpointFor(int endpoint, bool rx, bool tx,
777 bool handshake) {
778 uint8_t control = 0;
779 if (rx) {
780 control |= USB_ENDPT_EPRXEN;
781 }
782 if (tx) {
783 control |= USB_ENDPT_EPTXEN;
784 }
785 if (handshake) {
786 control |= USB_ENDPT_EPHSHK;
787 }
788 USB0_ENDPTn(endpoint) = control;
789}
790
791int UsbFunction::AddEndpoint() {
792 const int r = device_->endpoint_mapping_.size();
793 assert(r < number_endpoints());
794 device_->endpoint_mapping_.push_back(this);
795 return r;
796}
797
798int UsbFunction::AddInterface() {
799 const int r = device_->interface_mapping_.size();
800 // bInterfaceNumber is only one byte.
801 assert(r < 255);
802 device_->interface_mapping_.push_back(this);
803 return r;
804}
805
806void UsbDevice::SetBdtEntry(int endpoint, Direction direction, EvenOdd odd,
807 BdtEntry bdt_entry) {
808 *MutableBdtEntry(endpoint, direction, odd) = bdt_entry;
809}
810
811} // namespace teensy
812} // namespace frc971