blob: 0a05fad3254a09e80dd1c44674c9e9d3d87d13ca [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:
644 if (!in || recipient != standard_setup_recipients::kDevice) {
645 break;
646 }
647 const uint8_t descriptor_type_byte = (setup_packet.value >> 8) & 0xFF;
648 if (descriptor_type_byte < kUsbDescriptorTypeMin ||
649 descriptor_type_byte > kUsbDescriptorTypeMax) {
650 break;
651 }
652 const UsbDescriptorType descriptor_type =
653 static_cast<UsbDescriptorType>(descriptor_type_byte);
654 const uint8_t descriptor_index = setup_packet.value & 0xFF;
655 switch (descriptor_type) {
656 case UsbDescriptorType::kDevice:
657 if (setup_packet.index != 0 || descriptor_index != 0) {
658 break;
659 }
660 QueueEndpoint0Data(
661 device_descriptor_list_.data_.data(),
662 ::std::min<int>(setup_packet.length,
663 device_descriptor_list_.data_.size()));
664 return;
665
666 case UsbDescriptorType::kConfiguration:
667 if (setup_packet.index != 0 || descriptor_index != 0) {
668 break;
669 }
670 QueueEndpoint0Data(
671 config_descriptor_list_.data_.data(),
672 ::std::min<int>(setup_packet.length,
673 config_descriptor_list_.data_.size()));
674 return;
675
676 case UsbDescriptorType::kString:
677 if (descriptor_index != 0 && setup_packet.index != english_us_code()) {
678 break;
679 }
680 if (descriptor_index >= strings_.size()) {
681 break;
682 }
683 QueueEndpoint0Data(
684 strings_[descriptor_index].data(),
685 ::std::min<int>(setup_packet.length,
686 strings_[descriptor_index].size()));
687 return;
688
689 default:
690 // TODO(Brian): Handle other types of descriptor too.
691 break;
692 }
693 }
694 break;
695
696 default:
697 for (UsbFunction *function : functions_) {
698 switch (function->HandleEndpoint0SetupPacket(setup_packet)) {
699 case SetupResponse::kIgnored:
700 continue;
701 case SetupResponse::kHandled:
702 return;
703 case SetupResponse::kStall:
704 break;
705 }
706 break;
707 }
708 break;
709 }
710
711 StallEndpoint0();
712}
713
714// We're supposed to continue returning stalls until the next kSetup packet.
715// Code might continue putting stuff in the TX buffers, but the hardware won't
716// actually send it as long as the EPSTALL bit is set.
717void UsbDevice::StallEndpoint0() {
718 USB0_ENDPT0 = USB_ENDPT_EPSTALL | USB_ENDPT_EPRXEN | USB_ENDPT_EPTXEN |
719 USB_ENDPT_EPHSHK;
720}
721
722bool UsbDevice::BufferEndpoint0TxPacket() {
723 if (endpoint0_data_ == nullptr) {
724 return false;
725 }
726
727 const int to_transmit = ::std::min(endpoint0_data_left_, kEndpoint0MaxSize);
728 BdtEntry *const tx_bdt_entry =
729 MutableBdtEntry(0, Direction::kTx, endpoint0_tx_odd_);
730 // const_cast is safe because the hardware is only going to read from
731 // this, not write.
732 tx_bdt_entry->address =
733 const_cast<void *>(static_cast<const void *>(endpoint0_data_));
734 dma_memory_barrier();
735 tx_bdt_entry->buffer_descriptor =
736 V_USB_BD_BC(to_transmit) | static_cast<uint32_t>(endpoint0_tx_toggle_) |
737 M_USB_BD_OWN | M_USB_BD_DTS;
738
739 endpoint0_tx_odd_ = EvenOddInverse(endpoint0_tx_odd_);
740 endpoint0_tx_toggle_ = Data01Inverse(endpoint0_tx_toggle_);
741
742 endpoint0_data_ += to_transmit;
743 endpoint0_data_left_ -= to_transmit;
744 if (to_transmit < kEndpoint0MaxSize) {
745 endpoint0_data_ = nullptr;
746 }
747
748 return true;
749}
750
751void UsbDevice::SendEmptyEndpoint0Packet() {
752 // Really doesn't matter what we put here as long as it's not nullptr.
753 endpoint0_data_ = reinterpret_cast<char *>(this);
754 endpoint0_data_left_ = 0;
755 BufferEndpoint0TxPacket();
756}
757
758void UsbDevice::QueueEndpoint0Data(const char *data, int size) {
759 endpoint0_data_ = data;
760 endpoint0_data_left_ = size;
761 // There are 2 TX buffers, so fill them both up.
762 BufferEndpoint0TxPacket();
763 BufferEndpoint0TxPacket();
764}
765
766void UsbDevice::StallEndpoint(int endpoint) {
767 for (Direction direction : {Direction::kTx, Direction::kRx}) {
768 for (EvenOdd odd : {EvenOdd::kOdd, EvenOdd::kEven}) {
769 MutableBdtEntry(endpoint, direction, odd)->buffer_descriptor = 0;
770 dma_memory_barrier();
771 MutableBdtEntry(endpoint, direction, odd)->address = nullptr;
772 }
773 }
774 USB0_ENDPTn(endpoint) |= USB_ENDPT_EPSTALL;
775}
776
777void UsbDevice::ConfigureEndpointFor(int endpoint, bool rx, bool tx,
778 bool handshake) {
779 uint8_t control = 0;
780 if (rx) {
781 control |= USB_ENDPT_EPRXEN;
782 }
783 if (tx) {
784 control |= USB_ENDPT_EPTXEN;
785 }
786 if (handshake) {
787 control |= USB_ENDPT_EPHSHK;
788 }
789 USB0_ENDPTn(endpoint) = control;
790}
791
792int UsbFunction::AddEndpoint() {
793 const int r = device_->endpoint_mapping_.size();
794 assert(r < number_endpoints());
795 device_->endpoint_mapping_.push_back(this);
796 return r;
797}
798
799int UsbFunction::AddInterface() {
800 const int r = device_->interface_mapping_.size();
801 // bInterfaceNumber is only one byte.
802 assert(r < 255);
803 device_->interface_mapping_.push_back(this);
804 return r;
805}
806
807void UsbDevice::SetBdtEntry(int endpoint, Direction direction, EvenOdd odd,
808 BdtEntry bdt_entry) {
809 *MutableBdtEntry(endpoint, direction, odd) = bdt_entry;
810}
811
812} // namespace teensy
813} // namespace frc971