blob: 299df59cb52098dd70e96a04b53233afa120bbd9 [file] [log] [blame]
Brian Silvermanf91524f2017-09-23 13:15:55 -04001#ifndef MOTORS_USB_USB_H_
2#define MOTORS_USB_USB_H_
3
4#include <assert.h>
Brian Silvermand930f282017-11-04 23:09:12 -04005#include <string.h>
Brian Silvermanf91524f2017-09-23 13:15:55 -04006#include <string>
7#include <vector>
8#include <memory>
9
10#include "aos/common/macros.h"
11#include "motors/core/kinetis.h"
12#include "motors/usb/constants.h"
13
14namespace frc971 {
15namespace teensy {
16
17// A sufficient memory barrier between writing some data and telling the USB
18// hardware to read it or having the USB hardware say some data is readable and
19// actually reading it.
20static inline void dma_memory_barrier() {
21 __asm__ __volatile__("" :: : "memory");
22}
23
24// Aligned for faster access via memcpy etc.
Brian Silverman69f96c22017-11-01 02:54:02 -040025//
26// Also, the Freescale example stack forces aligned buffers to work around some
27// hardware limitations which may or may not apply to our chips.
Brian Silvermanf91524f2017-09-23 13:15:55 -040028typedef void *DataPointer __attribute__((aligned(4)));
29
30// An entry in the Buffer Descriptor Table.
31struct BdtEntry {
32 uint32_t buffer_descriptor;
33 DataPointer address;
34};
35
36#define V_USB_BD_BC(value) \
37 static_cast<uint32_t>(static_cast<uint32_t>(value) << 16)
38#define G_USB_BD_BC(bd) (((bd) >> 16) & UINT32_C(0x3FF))
39#define M_USB_BD_OWN UINT32_C(1 << 7)
40#define M_USB_BD_DATA1 UINT32_C(1 << 6)
41static_assert(static_cast<uint32_t>(Data01::kData1) == M_USB_BD_DATA1,
42 "Wrong value");
43#define M_USB_BD_KEEP UINT32_C(1 << 5)
44#define M_USB_BD_NINC UINT32_C(1 << 4)
45#define M_USB_BD_DTS UINT32_C(1 << 3)
46#define M_USB_BD_STALL UINT32_C(1 << 2)
47#define V_USB_BD_PID(value) \
48 static_cast<uint32_t>(static_cast<uint32_t>(value) << 2)
49#define G_USB_BD_PID(bd) static_cast<UsbPid>(((bd) >> 2) & UINT32_C(0xF))
50
51#define G_USB_STAT_ENDP(stat) (((stat) >> 4) & UINT32_C(0xF))
52#define M_USB_STAT_TX UINT32_C(1 << 3)
53#define M_USB_STAT_ODD UINT32_C(1 << 2)
54
55// The various types of descriptors defined in the standard for retrieval via
56// GetDescriptor.
57static constexpr uint8_t kUsbDescriptorTypeMin = 1;
58static constexpr uint8_t kUsbDescriptorTypeMax = 11;
59enum class UsbDescriptorType : uint8_t {
60 kDevice = 1,
61 kConfiguration = 2,
62 kString = 3,
63 kInterface = 4,
64 kEndpoint = 5,
65 kDeviceQualifier = 6,
66 kOtherSpeedConfiguration = 7,
67 kInterfacePower = 8,
68 kOtg = 9,
69 kDebug = 10,
70 kInterfaceAssociation = 11,
71};
72
73// The class-specific descriptor types.
74enum class UsbClassDescriptorType : uint8_t {
75 kDevice = 0x21,
76 kConfiguration = 0x22,
77 kString = 0x23,
78 kInterface = 0x24,
79 kEndpoint = 0x25,
Brian Silvermand930f282017-11-04 23:09:12 -040080
81 kHidHid = 0x21,
82 kHidReport = 0x22,
83 kHidPhysical = 0x23,
Brian Silvermanf91524f2017-09-23 13:15:55 -040084};
85
86// The names of the setup request types from the standard.
87enum class SetupRequestType {
88 kStandard = 0,
89 kClass = 1,
90 kVendor = 2,
91 kReserved = 3,
92};
93
94// Set means device-to-host, clear means host-to-device.
95#define M_SETUP_REQUEST_TYPE_IN UINT8_C(1 << 7)
96#define G_SETUP_REQUEST_TYPE_TYPE(type) \
97 static_cast<SetupRequestType>(((type) >> 5) & UINT8_C(3))
98#define G_SETUP_REQUEST_TYPE_RECIPIENT(type) ((type)&UINT8_C(0x1F))
99#define G_SETUP_REQUEST_INDEX_ENDPOINT(index) ((index)&UINT8_C(0x7F))
100
101// The names of the standard recipients for setup requests.
102namespace standard_setup_recipients {
103constexpr int kDevice = 0;
104constexpr int kInterface = 1;
105constexpr int kEndpoint = 2;
106constexpr int kOther = 3;
107} // namespace standard_setup_recipients
108
Brian Silverman4aa83042018-01-05 12:47:31 -0800109namespace microsoft_feature_descriptors {
110constexpr int kExtendedCompatibilityId = 4;
111constexpr int kExtendedProperties = 5;
112} // namespace microsoft_feature_descriptors
113
Brian Silvermand930f282017-11-04 23:09:12 -0400114// The HID class specification says this. Can't find any mention in the main
115// standard.
116#define G_DESCRIPTOR_TYPE_TYPE(descriptor_type) \
117 ((descriptor_type) >> 5 & UINT8_C(3))
118namespace standard_descriptor_type_types {
119constexpr int kStandard = 0;
120constexpr int kClass = 1;
121constexpr int kVendor = 2;
122} // namespace standard_descriptor_type_types
123
Brian Silverman4aa83042018-01-05 12:47:31 -0800124constexpr uint8_t vendor_specific_class() { return 0xFF; }
125
Brian Silvermanf91524f2017-09-23 13:15:55 -0400126class UsbFunction;
127
128// Allows building up a list of descriptors. This supports a much nicer API than
129// the usual "hard-code a char[] with all the sizes and offsets at compile
130// time". Space for each descriptor is reserved, and then it may be filled out
131// from beginning to end at any time.
132//
133// An instance is the thing that the GetDescriptor operation sends to the host.
134// This is not the concept that the core and class standards call "Foo
135// Descriptor" etc; see Descriptor for that.
136class UsbDescriptorList {
137 public:
138 // Represents a single descriptor. All of the contents must be written before
139 // this object is destroyed.
140 //
141 // Create one via UsbDescriptorList::CreateDescriptor.
142 class Descriptor {
143 public:
144 // All of the allocated space must be filled first.
145 ~Descriptor() {
146 if (descriptor_list_ == nullptr) {
147 return;
148 }
149 // Verify we wrote all the bytes first.
150 assert(next_index_ == end_index_);
151 --descriptor_list_->open_descriptors_;
152 }
153
154 void AddUint16(uint16_t value) {
155 AddByte(value & 0xFF);
156 AddByte((value >> 8) & 0xFF);
157 }
158
159 void AddByte(uint8_t value) {
160 assert(next_index_ < end_index_);
161 data()[next_index_] = value;
162 ++next_index_;
163 }
164
165 // Overwrites an already-written byte.
166 void SetByte(int index, uint8_t value) {
167 assert(index + start_index_ < end_index_);
168 data()[index + start_index_] = value;
169 }
170
171 private:
172 Descriptor(UsbDescriptorList *descriptor_list, int start_index,
173 int end_index)
174 : descriptor_list_(descriptor_list),
175 start_index_(start_index),
176 end_index_(end_index),
177 next_index_(start_index_) {}
178
179 char *data() const {
180 return &descriptor_list_->data_[0];
181 }
182
183 UsbDescriptorList *const descriptor_list_;
184 const int start_index_, end_index_;
185 int next_index_;
186
187 friend class UsbDescriptorList;
188
189 DISALLOW_COPY_AND_ASSIGN(Descriptor);
190 };
191
192 UsbDescriptorList() = default;
193 ~UsbDescriptorList() = default;
194
195 // Creates a new descriptor at the end of the list.
196 // length is the number of bytes, including the length byte.
197 // descriptor_type is the descriptor type, which is the second byte after the
198 // length.
199 ::std::unique_ptr<Descriptor> CreateDescriptor(
200 uint8_t length, UsbDescriptorType descriptor_type) {
201 return CreateDescriptor(length, static_cast<uint8_t>(descriptor_type));
202 }
203
204 ::std::unique_ptr<Descriptor> CreateDescriptor(
205 uint8_t length, UsbClassDescriptorType descriptor_type) {
206 assert(data_.size() > 0);
207 return CreateDescriptor(length, static_cast<uint8_t>(descriptor_type));
208 }
209
Brian Silvermand930f282017-11-04 23:09:12 -0400210 void AddPremadeDescriptor(const uint8_t *data, int length) {
211 const int start_index = data_.size();
212 const int end_index = start_index + length;
213 data_.resize(end_index);
214 memcpy(&data_[start_index], data, length);
215 }
216
Brian Silverman587edcc2018-01-15 12:00:22 -0800217 void AddPremadeDescriptor(const UsbDescriptorList &other_list) {
218 other_list.CheckFinished();
219 AddPremadeDescriptor(
220 reinterpret_cast<const uint8_t *>(other_list.data_.data()),
221 other_list.data_.size());
222 }
223
Brian Silvermanf91524f2017-09-23 13:15:55 -0400224 void CheckFinished() const { assert(open_descriptors_ == 0); }
225
226 int CurrentSize() const { return data_.size(); }
227
Brian Silverman587edcc2018-01-15 12:00:22 -0800228 const char *GetData() const {
229 CheckFinished();
230 return data_.data();
231 }
232
Brian Silvermanf91524f2017-09-23 13:15:55 -0400233 private:
234 ::std::unique_ptr<Descriptor> CreateDescriptor(uint8_t length,
235 uint8_t descriptor_type) {
236 const int start_index = data_.size();
237 const int end_index = start_index + length;
238 data_.resize(end_index);
239 ++open_descriptors_;
240 auto r = ::std::unique_ptr<Descriptor>(
241 new Descriptor(this, start_index, end_index));
242 r->AddByte(length); // bLength
243 r->AddByte(descriptor_type); // bDescriptorType
244 return r;
245 }
246
247 int open_descriptors_ = 0;
248
249 ::std::string data_;
250
251 friend class UsbDevice;
252
253 DISALLOW_COPY_AND_ASSIGN(UsbDescriptorList);
254};
255
256extern "C" void usb_isr(void);
257
258// USB state events are managed by asking each function if it wants to handle
259// them, sequentially. For the small number of functions which can be
260// practically supported with the limited number of endpoints, this performs
261// better than fancier things like hash maps.
262
263// Manages one of the Teensy's USB peripherals as a USB slave device.
264//
265// This supports being a composite device with multiple functions.
266//
267// Attaching functions etc is called "setup", and must be completed before
268// Initialize() is called.
269//
270// Detaching functions is called "teardown" and must happen after Shutdown().
271// TODO(Brian): Implement Shutdown().
272class UsbDevice final {
273 public:
274 // Represents the data that comes with a UsbPid::kSetup.
275 // Note that the order etc is important because we memcpy into this.
276 struct SetupPacket {
277 uint8_t request_type; // bmRequestType
278 uint8_t request; // bRequest
279 uint16_t value; // wValue
280 uint16_t index; // wIndex
281 uint16_t length; // wLength
282 } __attribute__((aligned(4)));
283 static_assert(sizeof(SetupPacket) == 8, "wrong size");
284
285 enum class SetupResponse {
286 // Indicates this function doesn't recognize the setup packet.
287 kIgnored,
288
289 // Indicates the endpoint should be stalled.
290 //
291 // Don't return this if the packet is for another function.
292 kStall,
293
294 // Indicates this setup packet was handled. Functions must avoid eating
295 // packets intended for other functions.
296 kHandled,
297 };
298
299 static constexpr int kEndpoint0MaxSize = 64;
300
301 // The only language code we support.
302 static constexpr uint16_t english_us_code() { return 0x0409; }
303
304 UsbDevice(int index, uint16_t vendor_id, uint16_t product_id);
305 ~UsbDevice();
306
307 // Ends setup and starts being an actual USB device.
308 void Initialize();
309
310 // Adds a string to the table and returns its index.
311 //
312 // For simplicity, we only support strings with english_us_code().
313 //
314 // May only be called during setup.
315 int AddString(const ::std::string &string) {
316 assert(!is_set_up_);
317 const int r = strings_.size();
318 strings_.emplace_back(string.size() * 2 + 2, '\0');
319 strings_.back()[0] = 2 + string.size() * 2;
320 strings_.back()[1] = static_cast<uint8_t>(UsbDescriptorType::kString);
321 for (size_t i = 0; i < string.size(); ++i) {
322 strings_.back()[i * 2 + 2] = string[i];
323 }
324 return r;
325 }
326
327 // Sets the manufacturer string.
328 //
329 // May only be called during setup.
330 void SetManufacturer(const ::std::string &string) {
331 device_descriptor_->SetByte(14, AddString(string)); // iManufacturer
332 }
333
334 // Sets the product string.
335 //
336 // May only be called during setup.
337 void SetProduct(const ::std::string &string) {
338 device_descriptor_->SetByte(15, AddString(string)); // iProduct
339 }
340
341 // Sets the serial number string.
342 //
343 // May only be called during setup.
344 void SetSerialNumber(const ::std::string &string) {
345 device_descriptor_->SetByte(16, AddString(string)); // iSerialNumber
346 }
347
348 // Queues up an empty IN packet for endpoint 0. This is a common way to
349 // respond to various kinds of configuration commands.
350 //
351 // This may only be called from the appropriate function callbacks.
352 void SendEmptyEndpoint0Packet();
353
354 // Queues some data to send on endpoint 0. This includes putting the initial
355 // packets into the TX buffers.
356 //
357 // This may only be called from the appropriate function callbacks.
358 void QueueEndpoint0Data(const char *data, int size);
359
360 // Stalls an endpoint until it's cleared.
361 //
362 // This should only be called by or on behalf of the function which owns
363 // endpoint.
364 void StallEndpoint(int endpoint);
365
366 // Configures an endpoint to send and/or receive, with or without DATA0/DATA1
367 // handshaking. handshake should probably be true for everything except
368 // isochronous endpoints.
369 //
370 // This should only be called by or on behalf of the function which owns
371 // endpoint.
372 void ConfigureEndpointFor(int endpoint, bool rx, bool tx, bool handshake);
373
374 void SetBdtEntry(int endpoint, Direction direction, EvenOdd odd,
375 BdtEntry bdt_entry);
376
377 private:
378 // Clears all pending interrupts.
379 void ClearInterrupts();
380
381 // Deals with an interrupt that has occured.
382 void HandleInterrupt();
383
384 // Processes a token on endpoint 0.
385 void HandleEndpoint0Token(uint8_t stat);
386
387 // Processes a setup packet on endpoint 0.
388 void HandleEndpoint0SetupPacket(const SetupPacket &setup_packet);
389
390 // Sets endpoint 0 to return STALL tokens. We clear this condition upon
391 // receiving the next SETUP token.
392 void StallEndpoint0();
393
394 // Places the first packet from {endpoint0_data_, endpoint0_data_left_} into
395 // the TX buffers (if there is any data). This may only be called when the
396 // next TX buffer is empty.
397 bool BufferEndpoint0TxPacket();
398
399 // Which USB peripheral this is.
400 const int index_;
401
402 // The string descriptors in order.
403 ::std::vector<::std::string> strings_;
404
405 // TODO(Brian): Refactor into something more generic, because I think this is
406 // shared with all non-isochronous endpoints?
407 Data01 endpoint0_tx_toggle_;
408 EvenOdd endpoint0_tx_odd_;
409 uint8_t endpoint0_receive_buffer_[2][kEndpoint0MaxSize]
410 __attribute__((aligned(4)));
411
412 // A temporary buffer for holding data to transmit on endpoint 0. Sometimes
413 // this is used and sometimes the data is sent directly from some other
414 // location (like for descriptors).
415 char endpoint0_transmit_buffer_[kEndpoint0MaxSize];
416
417 // The data we're waiting to send from endpoint 0. The data must remain
418 // constant until this transmission is done.
419 //
420 // When overwriting this, we ignore if it's already non-nullptr. The host is
421 // supposed to read all of the data before asking for more. If it doesn't do
422 // that, it will just get garbage data because it's unclear what it expects.
423 //
424 // Do note that endpoint0_data_ != nullptr && endpoint0_data_left_ == 0 is an
425 // important state. This means we're going to return a 0-length packet the
426 // next time the host asks. However, depending on the length it asked for,
427 // that might never happen.
428 const char *endpoint0_data_ = nullptr;
429 int endpoint0_data_left_ = 0;
430
431 // If non-0, the new address we're going to start using once the status stage
432 // of the current setup request is finished.
433 uint16_t new_address_ = 0;
434
435 UsbDescriptorList device_descriptor_list_;
436 UsbDescriptorList config_descriptor_list_;
437
438 ::std::unique_ptr<UsbDescriptorList::Descriptor> device_descriptor_,
439 config_descriptor_;
440
441 int configuration_ = 0;
442
443 bool is_set_up_ = false;
444
445 // The function which owns each endpoint.
446 ::std::vector<UsbFunction *> endpoint_mapping_;
447 // The function which owns each interface.
448 ::std::vector<UsbFunction *> interface_mapping_;
449 // All of the functions (without duplicates).
450 ::std::vector<UsbFunction *> functions_;
451
Brian Silverman4aa83042018-01-05 12:47:31 -0800452 // Filled out during Initialize().
453 ::std::string microsoft_extended_id_descriptor_;
454
Brian Silvermanf91524f2017-09-23 13:15:55 -0400455 friend void usb_isr(void);
456 friend class UsbFunction;
457};
458
459// Represents a USB function. This consists of a set of descriptors and
460// interfaces.
461//
462// Each instance is a single function, so there can be multiple instances of the
463// same subclass in the same devices (ie two serial ports).
464class UsbFunction {
465 public:
466 UsbFunction(UsbDevice *device) : device_(device) {
467 device_->functions_.push_back(this);
468 }
469 virtual ~UsbFunction() = default;
470
471 protected:
472 using SetupResponse = UsbDevice::SetupResponse;
473
474 static constexpr uint8_t iad_descriptor_length() { return 8; }
475 static constexpr uint8_t interface_descriptor_length() { return 9; }
476 static constexpr uint8_t endpoint_descriptor_length() { return 7; }
477
478 static constexpr uint8_t m_endpoint_address_in() { return 1 << 7; }
479 static constexpr uint8_t m_endpoint_attributes_control() { return 0x00; }
480 static constexpr uint8_t m_endpoint_attributes_isochronous() { return 0x01; }
Brian Silvermanf71c3332017-11-23 20:38:22 -0500481 static constexpr uint8_t m_endpoint_attributes_bulk() { return 0x02; }
Brian Silvermanf91524f2017-09-23 13:15:55 -0400482 static constexpr uint8_t m_endpoint_attributes_interrupt() { return 0x03; }
483
484 // Adds a new endpoint and returns its index.
485 //
486 // Note that at least one descriptor for this newly created endpoint must be
487 // added via CreateConfigDescriptor.
488 //
489 // TODO(Brian): Does this hardware actually only support a single direction
490 // per endpoint number, or can it get a total of 30 endpoints max?
491 //
492 // May only be called during setup.
493 int AddEndpoint();
494
495 // Adds a new interface and returns its index.
496 //
497 // You'll probably want to put this new interface in at least one descriptor
498 // added via CreateConfigDescriptor.
499 //
500 // May only be called during setup.
501 int AddInterface();
502
503 // Adds a new descriptor in the configuration descriptor list. See
504 // UsbDescriptorList::CreateDescriptor for details.
505 //
506 // Note that the order of calls to this is highly significant. In general,
507 // this should only be called from Initialize().
508 //
509 // May only be called during setup.
510 template <typename T>
511 ::std::unique_ptr<UsbDescriptorList::Descriptor> CreateDescriptor(
512 uint8_t length, T descriptor_type) {
513 return device_->config_descriptor_list_.CreateDescriptor(length,
514 descriptor_type);
515 }
Brian Silvermand930f282017-11-04 23:09:12 -0400516 void AddPremadeDescriptor(const uint8_t *data, int length) {
517 device_->config_descriptor_list_.AddPremadeDescriptor(data, length);
518 }
Brian Silverman587edcc2018-01-15 12:00:22 -0800519 void AddPremadeDescriptor(const UsbDescriptorList &other_list) {
520 device_->config_descriptor_list_.AddPremadeDescriptor(other_list);
521 }
Brian Silvermanf91524f2017-09-23 13:15:55 -0400522
523 UsbDevice *device() const { return device_; }
524
Brian Silverman4aa83042018-01-05 12:47:31 -0800525 void CreateIadDescriptor(int first_interface, int interface_count,
526 int function_class, int function_subclass,
527 int function_protocol,
528 const ::std::string &function);
529
530 // Sets the interface GUIDs for this function. Each GUID (one per interface?)
531 // should be followed by a NUL.
532 //
533 // If this is never called, no GUID extended property will be reported.
534 //
535 // This is needed to pass to Windows so WinUSB will be happy. Generate them at
536 // https://www.guidgenerator.com/online-guid-generator.aspx (Uppcase, Braces,
537 // and Hyphens).
538 //
539 // May only be called during setup.
540 void SetMicrosoftDeviceInterfaceGuids(const ::std::string &guids);
541
Brian Silvermanf91524f2017-09-23 13:15:55 -0400542 private:
543 virtual void Initialize() = 0;
544
545 virtual SetupResponse HandleEndpoint0SetupPacket(
546 const UsbDevice::SetupPacket & /*setup_packet*/) {
547 return SetupResponse::kIgnored;
548 }
549
550 virtual SetupResponse HandleEndpoint0OutPacket(void * /*data*/,
551 int /*data_length*/) {
552 return SetupResponse::kIgnored;
553 }
554
Brian Silvermand930f282017-11-04 23:09:12 -0400555 virtual SetupResponse HandleGetDescriptor(
556 const UsbDevice::SetupPacket & /*setup_packet*/) {
557 return SetupResponse::kIgnored;
558 }
559
Brian Silverman4aa83042018-01-05 12:47:31 -0800560 // Returns the concatenated compatible ID and subcompatible ID.
561 virtual ::std::string MicrosoftExtendedCompatibleId() {
562 // Default to both of them being "unused".
563 return ::std::string(16, '\0');
564 }
565
566 virtual void HandleOutFinished(int /*endpoint*/, BdtEntry * /*bdt_entry*/) {}
567 virtual void HandleInFinished(int /*endpoint*/, BdtEntry * /*bdt_entry*/,
568 EvenOdd /*odd*/) {}
Brian Silvermanf91524f2017-09-23 13:15:55 -0400569
570 // Called when a given interface is configured (aka "experiences a
571 // configuration event"). This means all rx and tx buffers have been cleared
572 // and should be filled as appropriate, starting from data0. Also,
573 // ConfigureEndpointFor should be called with the appropriate arguments.
574 virtual void HandleConfigured(int endpoint) = 0;
575
576 // Should reset everything to use the even buffers next.
577 virtual void HandleReset() = 0;
578
Brian Silverman4aa83042018-01-05 12:47:31 -0800579 int first_interface_ = -1;
580
581 // Filled out during Initialize().
582 ::std::string microsoft_extended_property_descriptor_;
583
Brian Silvermanf91524f2017-09-23 13:15:55 -0400584 UsbDevice *const device_;
585
586 friend class UsbDevice;
587};
588
589} // namespace teensy
590} // namespace frc971
591
592#endif // MOTORS_USB_USB_H_