blob: fb7fe9f661df43f6c71b59a36ac032feccaaa599 [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;
Brian Silverman69f96c22017-11-01 02:54:02 -0400253 USB0_ISTAT = USB_ISTAT_TOKDNE;
Brian Silvermanf91524f2017-09-23 13:15:55 -0400254 const int endpoint = G_USB_STAT_ENDP(stat);
255
256 if (endpoint == 0) {
257 HandleEndpoint0Token(stat);
258 } else {
259 BdtEntry *const bdt_entry = MutableBdtEntryFromStat(stat);
260 const UsbPid pid = G_USB_BD_PID(bdt_entry->buffer_descriptor);
261 UsbFunction *const function = endpoint_mapping_[endpoint];
262 if (function == nullptr) {
263 // Should never happen, so stall if we do get here somehow.
264 StallEndpoint(endpoint);
265 } else {
266 switch (pid) {
267 case UsbPid::kOut:
268 function->HandleOutFinished(endpoint, bdt_entry);
269 break;
270
271 case UsbPid::kIn:
272 function->HandleInFinished(
273 endpoint, bdt_entry,
274 (stat & M_USB_STAT_ODD) ? EvenOdd::kOdd : EvenOdd::kEven);
275 break;
276
277 case UsbPid::kSetup:
278 default:
279 // Should never happen, so stall if we do get here somehow.
280 StallEndpoint(endpoint);
281 break;
282 }
283 }
284 }
Brian Silvermanf91524f2017-09-23 13:15:55 -0400285 }
286
287 if (status & USB_ISTAT_USBRST) {
288 // Use DATA0 for all endpoints.
289 USB0_CTL = USB_CTL_ODDRST;
290 endpoint0_tx_odd_ = EvenOdd::kEven;
291 endpoint0_tx_toggle_ = Data01::kData0;
292
293 for (UsbFunction *function : functions_) {
294 function->HandleReset();
295 }
296
297 MutableBdtEntry(0, Direction::kRx, EvenOdd::kEven)->buffer_descriptor =
298 M_USB_BD_OWN | M_USB_BD_DTS | V_USB_BD_BC(kEndpoint0MaxSize);
299 MutableBdtEntry(0, Direction::kRx, EvenOdd::kEven)->address =
300 &endpoint0_receive_buffer_[0][0];
301
302 MutableBdtEntry(0, Direction::kRx, EvenOdd::kOdd)->buffer_descriptor =
303 M_USB_BD_OWN | M_USB_BD_DTS | V_USB_BD_BC(kEndpoint0MaxSize);
304 MutableBdtEntry(0, Direction::kRx, EvenOdd::kOdd)->address =
305 &endpoint0_receive_buffer_[1][0];
306
307 MutableBdtEntry(0, Direction::kTx, EvenOdd::kEven)->buffer_descriptor = 0;
308 MutableBdtEntry(0, Direction::kTx, EvenOdd::kOdd)->buffer_descriptor = 0;
309
310 USB0_ENDPT0 = USB_ENDPT_EPRXEN | USB_ENDPT_EPTXEN | USB_ENDPT_EPHSHK;
311
312 ClearInterrupts();
313
314 // Set the address to 0 for enumeration.
315 USB0_ADDR = 0;
316 new_address_ = 0;
317
318 endpoint0_data_ = nullptr;
319 endpoint0_data_left_ = 0;
320
321 USB0_INTEN = usb_enabled_interrupts();
322 USB0_ERREN = USB_ERREN_BTSERREN | USB_ERREN_DMAERREN |
323 USB_ERREN_BTOERREN | USB_ERREN_DFN8EN | USB_ERREN_CRC16EN |
324 USB_ERREN_CRC5EOFEN | USB_ERREN_PIDERREN;
325
326 // Start the peripheral going.
327 dma_memory_barrier();
328 USB0_CTL = USB_CTL_USBENSOFEN;
329
330 continue;
331 }
332
333 // TODO(Brian): Handle errors more intelligently.
334 if (status & USB_ISTAT_ERROR) {
335 const uint8_t error = USB0_ERRSTAT;
336 USB0_ERRSTAT = error;
337 USB0_ISTAT = USB_ISTAT_ERROR;
338 }
339 }
340}
341
342void UsbDevice::HandleEndpoint0Token(const uint8_t stat) {
343 BdtEntry *const bdt_entry = MutableBdtEntryFromStat(stat);
344 const UsbPid pid = G_USB_BD_PID(bdt_entry->buffer_descriptor);
345 switch (pid) {
346 case UsbPid::kSetup:
347 // Unstall it if it was previously stalled.
348 USB0_ENDPT0 = USB_ENDPT_EPRXEN | USB_ENDPT_EPTXEN | USB_ENDPT_EPHSHK;
349
350 SetupPacket setup_packet;
351 memcpy(&setup_packet, bdt_entry->address, sizeof(setup_packet));
352
353 // Give the buffer back now.
354 dma_memory_barrier();
355 // Next IN and OUT packet for this endpoint (data stage/status stage)
356 // should both be DATA1.
Brian Silvermanf91524f2017-09-23 13:15:55 -0400357 MutableBdtEntryFromStat(stat ^ M_USB_STAT_ODD)->buffer_descriptor =
358 M_USB_BD_OWN | M_USB_BD_DTS | V_USB_BD_BC(kEndpoint0MaxSize) |
359 M_USB_BD_DATA1;
360 endpoint0_tx_toggle_ = Data01::kData1;
361
Brian Silverman69f96c22017-11-01 02:54:02 -0400362 // Give this buffer back. It should be DATA0 because it'll be the second
363 // received packet.
364 bdt_entry->buffer_descriptor =
365 M_USB_BD_OWN | M_USB_BD_DTS | V_USB_BD_BC(kEndpoint0MaxSize);
366
Brian Silvermanf91524f2017-09-23 13:15:55 -0400367 // TODO(Brian): Tell the functions a new setup packet is starting.
368 // CdcTty: next_endpoint0_out_ = NextEndpoint0Out::kNone;
369
370 // Forget about any pending transactions on this endpoint. There shouldn't
371 // be any, so if we think there are something's out of sync and we should
372 // just drop it. Important to do this before clearing TXD_SUSPEND in
373 // USBx_CTL. Standard says "If a Setup transaction is received by an
374 // endpoint before a previously initiated control transfer is completed,
375 // the device must abort the current transfer/operation".
376 endpoint0_data_ = nullptr;
377 endpoint0_data_left_ = 0;
378 MutableBdtEntry(0, Direction::kTx, EvenOdd::kEven)->buffer_descriptor = 0;
379 MutableBdtEntry(0, Direction::kTx, EvenOdd::kOdd)->buffer_descriptor = 0;
380
381 HandleEndpoint0SetupPacket(setup_packet);
382
383 break;
384
385 case UsbPid::kOut:
386 for (UsbFunction *function : functions_) {
387 switch (function->HandleEndpoint0OutPacket(
388 bdt_entry->address, G_USB_BD_BC(bdt_entry->buffer_descriptor))) {
389 case SetupResponse::kIgnored:
390 break;
391 case SetupResponse::kHandled:
392 dma_memory_barrier();
393 bdt_entry->buffer_descriptor =
394 M_USB_BD_OWN | M_USB_BD_DTS | V_USB_BD_BC(kEndpoint0MaxSize);
395 return;
396 case SetupResponse::kStall:
397 bdt_entry->buffer_descriptor =
398 M_USB_BD_OWN | M_USB_BD_DTS | V_USB_BD_BC(kEndpoint0MaxSize);
399 StallEndpoint0();
400 return;
401 }
402 }
403 bdt_entry->buffer_descriptor =
404 M_USB_BD_OWN | M_USB_BD_DTS | V_USB_BD_BC(kEndpoint0MaxSize);
405 StallEndpoint0();
406 return;
407
408 case UsbPid::kIn:
409 // The functions are allowed to queue data in {endpoint0_data_,
410 // endpoint0_data_left_}, so this case deals with sending their data too.
411
412 // An IN transaction completed, so set up for the next one if appropriate.
413 if (!BufferEndpoint0TxPacket()) {
414 // After we're done, any further requests from the host should result in
415 // stalls (until the next setup token).
416 // TODO(Brian): Keep track of which direction it is and how much we've
417 // finished so we actually know when to stall it, both here and for
418 // kOut tokens.
419 //StallEndpoint0();
420 }
421
422 // If we have a new address, there is nothing left in the setup request
423 // besides a single IN packet forming the status stage, so we know the
424 // changes must be done now.
425 if (new_address_ != 0) {
426 USB0_ADDR = new_address_;
427 new_address_ = 0;
428 }
429
430 break;
431
432 default:
433 // Should never happen, but give the buffer back anyways if necessary.
434 if (!(bdt_entry->buffer_descriptor & M_USB_BD_OWN)) {
435 bdt_entry->buffer_descriptor =
436 M_USB_BD_OWN | M_USB_BD_DTS | V_USB_BD_BC(kEndpoint0MaxSize);
437 }
438 break;
439 }
440
441 // Clear the TXD_SUSPEND flag.
442 dma_memory_barrier();
443 USB0_CTL = USB_CTL_USBENSOFEN;
444}
445
446void UsbDevice::HandleEndpoint0SetupPacket(const SetupPacket &setup_packet) {
447 const bool in = setup_packet.request_type & M_SETUP_REQUEST_TYPE_IN;
448 const uint8_t recipient =
449 G_SETUP_REQUEST_TYPE_RECIPIENT(setup_packet.request_type);
450 switch (G_SETUP_REQUEST_TYPE_TYPE(setup_packet.request_type)) {
451 case SetupRequestType::kStandard:
452 switch (setup_packet.request) {
453 case standard_setup_requests::kSetAddress:
454 if (in || recipient != standard_setup_recipients::kDevice ||
455 setup_packet.index != 0 || setup_packet.length != 0) {
456 break;
457 }
458 new_address_ = setup_packet.value;
459 SendEmptyEndpoint0Packet();
460 return;
461
462 case standard_setup_requests::kSetConfiguration:
463 if (in || recipient != standard_setup_recipients::kDevice ||
464 setup_packet.index != 0 || setup_packet.length != 0) {
465 break;
466 }
467 configuration_ = setup_packet.value;
468
469 // No need to mess with endpoint0_tx_toggle_ because we reset it with
470 // each setup packet anyways.
471
472 for (int endpoint = 0;
473 endpoint < static_cast<int>(endpoint_mapping_.size());
474 ++endpoint) {
475 if (endpoint_mapping_[endpoint]) {
476 endpoint_mapping_[endpoint]->HandleConfigured(endpoint);
477 }
478 }
479
480 SendEmptyEndpoint0Packet();
481 return;
482
483 case standard_setup_requests::kClearFeature:
484 if (in || setup_packet.length != 0) {
485 break;
486 }
487 if (recipient == standard_setup_recipients::kEndpoint &&
488 setup_packet.value == standard_feature_selectors::kEndpointHalt) {
489 const int endpoint =
490 G_SETUP_REQUEST_INDEX_ENDPOINT(setup_packet.index);
491 // Our endpoint 0 doesn't support the halt feature because that's
492 // weird and not recommended by the standard.
493 if (endpoint == 0) {
494 break;
495 }
496 if (endpoint >= number_endpoints()) {
497 break;
498 }
499 USB0_ENDPTn(endpoint) &= ~USB_ENDPT_EPSTALL;
500 if (endpoint_mapping_[endpoint] != nullptr) {
501 endpoint_mapping_[endpoint]->HandleConfigured(endpoint);
502 }
503 SendEmptyEndpoint0Packet();
504 return;
505 }
506 // We should never get kDeviceRemoteWakeup because we don't advertise
507 // support for it in our configuration descriptors.
508 // We should never get kTestMode because we're not high-speed.
509 break;
510
511 case standard_setup_requests::kSetFeature:
512 if (in || setup_packet.length != 0) {
513 break;
514 }
515 if (recipient == standard_setup_recipients::kEndpoint &&
516 setup_packet.value == standard_feature_selectors::kEndpointHalt) {
517 const int endpoint =
518 G_SETUP_REQUEST_INDEX_ENDPOINT(setup_packet.index);
519 // Our endpoint 0 doesn't support the halt feature because that's
520 // weird and not recommended by the standard.
521 if (endpoint == 0) {
522 break;
523 }
524 if (endpoint >= number_endpoints()) {
525 break;
526 }
527 StallEndpoint(endpoint);
528 // TODO(Brian): Tell the appropriate function it's now stalled.
529 SendEmptyEndpoint0Packet();
530 return;
531 }
532 // We should never get kDeviceRemoteWakeup because we don't advertise
533 // support for it in our configuration descriptors.
534 // We should never get kTestMode because we're not high-speed.
535 break;
536
537 case standard_setup_requests::kGetConfiguration:
538 if (!in || recipient != standard_setup_recipients::kDevice ||
539 setup_packet.index != 0 || setup_packet.length != 1) {
540 break;
541 }
542 endpoint0_transmit_buffer_[0] = configuration_;
543 QueueEndpoint0Data(endpoint0_transmit_buffer_, 1);
544 return;
545
546 case standard_setup_requests::kGetInterface:
547 if (!in || recipient != standard_setup_recipients::kInterface ||
548 setup_packet.value != 0 || setup_packet.length != 1) {
549 break;
550 }
551 // Standard says it's unspecified in the default state and must
552 // respond with an error in the address state, so just do an error for
553 // both of them.
554 if (configuration_ == 0) {
555 break;
556 }
557 // TODO(Brian): Ask the appropriate function what alternate setting
558 // the interface has, and stall if there isn't one.
559 endpoint0_transmit_buffer_[0] = 0;
560 QueueEndpoint0Data(endpoint0_transmit_buffer_, 1);
561 return;
562
563 case standard_setup_requests::kSetInterface:
564 if (in || recipient != standard_setup_recipients::kInterface ||
565 setup_packet.length != 0) {
566 break;
567 }
568 // Standard says it's unspecified in the default state and must
569 // respond with an error in the address state, so just do an error for
570 // both of them.
571 if (configuration_ == 0) {
572 break;
573 }
574
575 // TODO(Brian): Pass to the appropriate function instead.
576 if (setup_packet.value != 0) {
577 break;
578 }
579 SendEmptyEndpoint0Packet();
580 return;
581
582 case standard_setup_requests::kGetStatus:
583 if (!in || setup_packet.value != 0 || setup_packet.length != 2) {
584 break;
585 }
586 if (recipient == standard_setup_recipients::kDevice) {
587 if (setup_packet.index != 0) {
588 break;
589 }
590 // Say that we're currently self powered.
591 endpoint0_transmit_buffer_[0] = 1;
592 endpoint0_transmit_buffer_[1] = 0;
593 QueueEndpoint0Data(endpoint0_transmit_buffer_, 2);
594 return;
595 }
596 if ((recipient == standard_setup_recipients::kInterface &&
597 setup_packet.index == 0) ||
598 (recipient == standard_setup_recipients::kEndpoint &&
599 G_SETUP_REQUEST_INDEX_ENDPOINT(setup_packet.index) == 0)) {
600 endpoint0_transmit_buffer_[0] = 0;
601 endpoint0_transmit_buffer_[1] = 0;
602 QueueEndpoint0Data(endpoint0_transmit_buffer_, 2);
603 return;
604 }
605 // Standard says it's unspecified in the default state and must
606 // respond with an error in the address state, so just do an error
607 // for both of them.
608 if (configuration_ == 0) {
609 break;
610 }
611
612 if (recipient == standard_setup_recipients::kInterface) {
613 // TODO(Brian): Check if it's actually an interface we have?
614 endpoint0_transmit_buffer_[0] = 0;
615 endpoint0_transmit_buffer_[1] = 0;
616 QueueEndpoint0Data(endpoint0_transmit_buffer_, 2);
617 return;
618 }
619
620 if (recipient == standard_setup_recipients::kEndpoint) {
621 const int endpoint =
622 G_SETUP_REQUEST_INDEX_ENDPOINT(setup_packet.index);
623 // TODO(Brian): Check if it's actually an endpoint we have?
624 if (USB0_ENDPTn(endpoint) & USB_ENDPT_EPSTALL) {
625 endpoint0_transmit_buffer_[0] = 1;
626 } else {
627 endpoint0_transmit_buffer_[0] = 0;
628 }
629 endpoint0_transmit_buffer_[1] = 0;
630 QueueEndpoint0Data(endpoint0_transmit_buffer_, 2);
631 return;
632 }
633 break;
634
635 case standard_setup_requests::kSetDescriptor:
636 // Not implementing anything for this.
637 break;
638
639 case standard_setup_requests::kSynchFrame:
640 // We don't implement any classes which use this.
641 break;
642
643 case standard_setup_requests::kGetDescriptor:
Brian Silvermand930f282017-11-04 23:09:12 -0400644 if (!in) {
Brian Silvermanf91524f2017-09-23 13:15:55 -0400645 break;
646 }
Brian Silvermand930f282017-11-04 23:09:12 -0400647
Brian Silvermanf91524f2017-09-23 13:15:55 -0400648 const uint8_t descriptor_type_byte = (setup_packet.value >> 8) & 0xFF;
Brian Silvermand930f282017-11-04 23:09:12 -0400649 if (G_DESCRIPTOR_TYPE_TYPE(descriptor_type_byte) !=
650 standard_descriptor_type_types::kStandard) {
651 for (UsbFunction *function : functions_) {
652 switch (function->HandleGetDescriptor(setup_packet)) {
653 case SetupResponse::kIgnored:
654 continue;
655 case SetupResponse::kHandled:
656 return;
657 case SetupResponse::kStall:
658 break;
659 }
660 break;
661 }
662 break;
663 }
664
665 if (recipient != standard_setup_recipients::kDevice) {
666 break;
667 }
Brian Silvermanf91524f2017-09-23 13:15:55 -0400668 if (descriptor_type_byte < kUsbDescriptorTypeMin ||
669 descriptor_type_byte > kUsbDescriptorTypeMax) {
670 break;
671 }
672 const UsbDescriptorType descriptor_type =
673 static_cast<UsbDescriptorType>(descriptor_type_byte);
674 const uint8_t descriptor_index = setup_packet.value & 0xFF;
675 switch (descriptor_type) {
676 case UsbDescriptorType::kDevice:
677 if (setup_packet.index != 0 || descriptor_index != 0) {
678 break;
679 }
680 QueueEndpoint0Data(
681 device_descriptor_list_.data_.data(),
682 ::std::min<int>(setup_packet.length,
683 device_descriptor_list_.data_.size()));
684 return;
685
686 case UsbDescriptorType::kConfiguration:
687 if (setup_packet.index != 0 || descriptor_index != 0) {
688 break;
689 }
690 QueueEndpoint0Data(
691 config_descriptor_list_.data_.data(),
692 ::std::min<int>(setup_packet.length,
693 config_descriptor_list_.data_.size()));
694 return;
695
696 case UsbDescriptorType::kString:
Brian Silvermand930f282017-11-04 23:09:12 -0400697 if (descriptor_index != 0 &&
698 setup_packet.index != english_us_code()) {
Brian Silvermanf91524f2017-09-23 13:15:55 -0400699 break;
700 }
701 if (descriptor_index >= strings_.size()) {
702 break;
703 }
704 QueueEndpoint0Data(
705 strings_[descriptor_index].data(),
706 ::std::min<int>(setup_packet.length,
707 strings_[descriptor_index].size()));
708 return;
709
710 default:
711 // TODO(Brian): Handle other types of descriptor too.
712 break;
713 }
714 }
715 break;
716
717 default:
718 for (UsbFunction *function : functions_) {
719 switch (function->HandleEndpoint0SetupPacket(setup_packet)) {
720 case SetupResponse::kIgnored:
721 continue;
722 case SetupResponse::kHandled:
723 return;
724 case SetupResponse::kStall:
725 break;
726 }
727 break;
728 }
729 break;
730 }
731
732 StallEndpoint0();
733}
734
735// We're supposed to continue returning stalls until the next kSetup packet.
736// Code might continue putting stuff in the TX buffers, but the hardware won't
737// actually send it as long as the EPSTALL bit is set.
738void UsbDevice::StallEndpoint0() {
739 USB0_ENDPT0 = USB_ENDPT_EPSTALL | USB_ENDPT_EPRXEN | USB_ENDPT_EPTXEN |
740 USB_ENDPT_EPHSHK;
741}
742
743bool UsbDevice::BufferEndpoint0TxPacket() {
744 if (endpoint0_data_ == nullptr) {
745 return false;
746 }
747
748 const int to_transmit = ::std::min(endpoint0_data_left_, kEndpoint0MaxSize);
749 BdtEntry *const tx_bdt_entry =
750 MutableBdtEntry(0, Direction::kTx, endpoint0_tx_odd_);
751 // const_cast is safe because the hardware is only going to read from
752 // this, not write.
753 tx_bdt_entry->address =
754 const_cast<void *>(static_cast<const void *>(endpoint0_data_));
755 dma_memory_barrier();
756 tx_bdt_entry->buffer_descriptor =
757 V_USB_BD_BC(to_transmit) | static_cast<uint32_t>(endpoint0_tx_toggle_) |
758 M_USB_BD_OWN | M_USB_BD_DTS;
759
760 endpoint0_tx_odd_ = EvenOddInverse(endpoint0_tx_odd_);
761 endpoint0_tx_toggle_ = Data01Inverse(endpoint0_tx_toggle_);
762
763 endpoint0_data_ += to_transmit;
764 endpoint0_data_left_ -= to_transmit;
765 if (to_transmit < kEndpoint0MaxSize) {
766 endpoint0_data_ = nullptr;
767 }
768
769 return true;
770}
771
772void UsbDevice::SendEmptyEndpoint0Packet() {
773 // Really doesn't matter what we put here as long as it's not nullptr.
774 endpoint0_data_ = reinterpret_cast<char *>(this);
775 endpoint0_data_left_ = 0;
776 BufferEndpoint0TxPacket();
777}
778
779void UsbDevice::QueueEndpoint0Data(const char *data, int size) {
780 endpoint0_data_ = data;
781 endpoint0_data_left_ = size;
782 // There are 2 TX buffers, so fill them both up.
783 BufferEndpoint0TxPacket();
784 BufferEndpoint0TxPacket();
785}
786
787void UsbDevice::StallEndpoint(int endpoint) {
788 for (Direction direction : {Direction::kTx, Direction::kRx}) {
789 for (EvenOdd odd : {EvenOdd::kOdd, EvenOdd::kEven}) {
790 MutableBdtEntry(endpoint, direction, odd)->buffer_descriptor = 0;
791 dma_memory_barrier();
792 MutableBdtEntry(endpoint, direction, odd)->address = nullptr;
793 }
794 }
795 USB0_ENDPTn(endpoint) |= USB_ENDPT_EPSTALL;
796}
797
798void UsbDevice::ConfigureEndpointFor(int endpoint, bool rx, bool tx,
799 bool handshake) {
800 uint8_t control = 0;
801 if (rx) {
802 control |= USB_ENDPT_EPRXEN;
803 }
804 if (tx) {
805 control |= USB_ENDPT_EPTXEN;
806 }
807 if (handshake) {
808 control |= USB_ENDPT_EPHSHK;
809 }
810 USB0_ENDPTn(endpoint) = control;
811}
812
813int UsbFunction::AddEndpoint() {
814 const int r = device_->endpoint_mapping_.size();
815 assert(r < number_endpoints());
816 device_->endpoint_mapping_.push_back(this);
817 return r;
818}
819
820int UsbFunction::AddInterface() {
821 const int r = device_->interface_mapping_.size();
822 // bInterfaceNumber is only one byte.
823 assert(r < 255);
824 device_->interface_mapping_.push_back(this);
825 return r;
826}
827
828void UsbDevice::SetBdtEntry(int endpoint, Direction direction, EvenOdd odd,
829 BdtEntry bdt_entry) {
830 *MutableBdtEntry(endpoint, direction, odd) = bdt_entry;
831}
832
833} // namespace teensy
834} // namespace frc971