blob: 8fd2fb391a6c44aba9868187d6b24f5eaf73576f [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 Silvermanf91524f2017-09-23 13:15:55 -0400217 void CheckFinished() const { assert(open_descriptors_ == 0); }
218
219 int CurrentSize() const { return data_.size(); }
220
221 private:
222 ::std::unique_ptr<Descriptor> CreateDescriptor(uint8_t length,
223 uint8_t descriptor_type) {
224 const int start_index = data_.size();
225 const int end_index = start_index + length;
226 data_.resize(end_index);
227 ++open_descriptors_;
228 auto r = ::std::unique_ptr<Descriptor>(
229 new Descriptor(this, start_index, end_index));
230 r->AddByte(length); // bLength
231 r->AddByte(descriptor_type); // bDescriptorType
232 return r;
233 }
234
235 int open_descriptors_ = 0;
236
237 ::std::string data_;
238
239 friend class UsbDevice;
240
241 DISALLOW_COPY_AND_ASSIGN(UsbDescriptorList);
242};
243
244extern "C" void usb_isr(void);
245
246// USB state events are managed by asking each function if it wants to handle
247// them, sequentially. For the small number of functions which can be
248// practically supported with the limited number of endpoints, this performs
249// better than fancier things like hash maps.
250
251// Manages one of the Teensy's USB peripherals as a USB slave device.
252//
253// This supports being a composite device with multiple functions.
254//
255// Attaching functions etc is called "setup", and must be completed before
256// Initialize() is called.
257//
258// Detaching functions is called "teardown" and must happen after Shutdown().
259// TODO(Brian): Implement Shutdown().
260class UsbDevice final {
261 public:
262 // Represents the data that comes with a UsbPid::kSetup.
263 // Note that the order etc is important because we memcpy into this.
264 struct SetupPacket {
265 uint8_t request_type; // bmRequestType
266 uint8_t request; // bRequest
267 uint16_t value; // wValue
268 uint16_t index; // wIndex
269 uint16_t length; // wLength
270 } __attribute__((aligned(4)));
271 static_assert(sizeof(SetupPacket) == 8, "wrong size");
272
273 enum class SetupResponse {
274 // Indicates this function doesn't recognize the setup packet.
275 kIgnored,
276
277 // Indicates the endpoint should be stalled.
278 //
279 // Don't return this if the packet is for another function.
280 kStall,
281
282 // Indicates this setup packet was handled. Functions must avoid eating
283 // packets intended for other functions.
284 kHandled,
285 };
286
287 static constexpr int kEndpoint0MaxSize = 64;
288
289 // The only language code we support.
290 static constexpr uint16_t english_us_code() { return 0x0409; }
291
292 UsbDevice(int index, uint16_t vendor_id, uint16_t product_id);
293 ~UsbDevice();
294
295 // Ends setup and starts being an actual USB device.
296 void Initialize();
297
298 // Adds a string to the table and returns its index.
299 //
300 // For simplicity, we only support strings with english_us_code().
301 //
302 // May only be called during setup.
303 int AddString(const ::std::string &string) {
304 assert(!is_set_up_);
305 const int r = strings_.size();
306 strings_.emplace_back(string.size() * 2 + 2, '\0');
307 strings_.back()[0] = 2 + string.size() * 2;
308 strings_.back()[1] = static_cast<uint8_t>(UsbDescriptorType::kString);
309 for (size_t i = 0; i < string.size(); ++i) {
310 strings_.back()[i * 2 + 2] = string[i];
311 }
312 return r;
313 }
314
315 // Sets the manufacturer string.
316 //
317 // May only be called during setup.
318 void SetManufacturer(const ::std::string &string) {
319 device_descriptor_->SetByte(14, AddString(string)); // iManufacturer
320 }
321
322 // Sets the product string.
323 //
324 // May only be called during setup.
325 void SetProduct(const ::std::string &string) {
326 device_descriptor_->SetByte(15, AddString(string)); // iProduct
327 }
328
329 // Sets the serial number string.
330 //
331 // May only be called during setup.
332 void SetSerialNumber(const ::std::string &string) {
333 device_descriptor_->SetByte(16, AddString(string)); // iSerialNumber
334 }
335
336 // Queues up an empty IN packet for endpoint 0. This is a common way to
337 // respond to various kinds of configuration commands.
338 //
339 // This may only be called from the appropriate function callbacks.
340 void SendEmptyEndpoint0Packet();
341
342 // Queues some data to send on endpoint 0. This includes putting the initial
343 // packets into the TX buffers.
344 //
345 // This may only be called from the appropriate function callbacks.
346 void QueueEndpoint0Data(const char *data, int size);
347
348 // Stalls an endpoint until it's cleared.
349 //
350 // This should only be called by or on behalf of the function which owns
351 // endpoint.
352 void StallEndpoint(int endpoint);
353
354 // Configures an endpoint to send and/or receive, with or without DATA0/DATA1
355 // handshaking. handshake should probably be true for everything except
356 // isochronous endpoints.
357 //
358 // This should only be called by or on behalf of the function which owns
359 // endpoint.
360 void ConfigureEndpointFor(int endpoint, bool rx, bool tx, bool handshake);
361
362 void SetBdtEntry(int endpoint, Direction direction, EvenOdd odd,
363 BdtEntry bdt_entry);
364
365 private:
366 // Clears all pending interrupts.
367 void ClearInterrupts();
368
369 // Deals with an interrupt that has occured.
370 void HandleInterrupt();
371
372 // Processes a token on endpoint 0.
373 void HandleEndpoint0Token(uint8_t stat);
374
375 // Processes a setup packet on endpoint 0.
376 void HandleEndpoint0SetupPacket(const SetupPacket &setup_packet);
377
378 // Sets endpoint 0 to return STALL tokens. We clear this condition upon
379 // receiving the next SETUP token.
380 void StallEndpoint0();
381
382 // Places the first packet from {endpoint0_data_, endpoint0_data_left_} into
383 // the TX buffers (if there is any data). This may only be called when the
384 // next TX buffer is empty.
385 bool BufferEndpoint0TxPacket();
386
387 // Which USB peripheral this is.
388 const int index_;
389
390 // The string descriptors in order.
391 ::std::vector<::std::string> strings_;
392
393 // TODO(Brian): Refactor into something more generic, because I think this is
394 // shared with all non-isochronous endpoints?
395 Data01 endpoint0_tx_toggle_;
396 EvenOdd endpoint0_tx_odd_;
397 uint8_t endpoint0_receive_buffer_[2][kEndpoint0MaxSize]
398 __attribute__((aligned(4)));
399
400 // A temporary buffer for holding data to transmit on endpoint 0. Sometimes
401 // this is used and sometimes the data is sent directly from some other
402 // location (like for descriptors).
403 char endpoint0_transmit_buffer_[kEndpoint0MaxSize];
404
405 // The data we're waiting to send from endpoint 0. The data must remain
406 // constant until this transmission is done.
407 //
408 // When overwriting this, we ignore if it's already non-nullptr. The host is
409 // supposed to read all of the data before asking for more. If it doesn't do
410 // that, it will just get garbage data because it's unclear what it expects.
411 //
412 // Do note that endpoint0_data_ != nullptr && endpoint0_data_left_ == 0 is an
413 // important state. This means we're going to return a 0-length packet the
414 // next time the host asks. However, depending on the length it asked for,
415 // that might never happen.
416 const char *endpoint0_data_ = nullptr;
417 int endpoint0_data_left_ = 0;
418
419 // If non-0, the new address we're going to start using once the status stage
420 // of the current setup request is finished.
421 uint16_t new_address_ = 0;
422
423 UsbDescriptorList device_descriptor_list_;
424 UsbDescriptorList config_descriptor_list_;
425
426 ::std::unique_ptr<UsbDescriptorList::Descriptor> device_descriptor_,
427 config_descriptor_;
428
429 int configuration_ = 0;
430
431 bool is_set_up_ = false;
432
433 // The function which owns each endpoint.
434 ::std::vector<UsbFunction *> endpoint_mapping_;
435 // The function which owns each interface.
436 ::std::vector<UsbFunction *> interface_mapping_;
437 // All of the functions (without duplicates).
438 ::std::vector<UsbFunction *> functions_;
439
Brian Silverman4aa83042018-01-05 12:47:31 -0800440 // Filled out during Initialize().
441 ::std::string microsoft_extended_id_descriptor_;
442
Brian Silvermanf91524f2017-09-23 13:15:55 -0400443 friend void usb_isr(void);
444 friend class UsbFunction;
445};
446
447// Represents a USB function. This consists of a set of descriptors and
448// interfaces.
449//
450// Each instance is a single function, so there can be multiple instances of the
451// same subclass in the same devices (ie two serial ports).
452class UsbFunction {
453 public:
454 UsbFunction(UsbDevice *device) : device_(device) {
455 device_->functions_.push_back(this);
456 }
457 virtual ~UsbFunction() = default;
458
459 protected:
460 using SetupResponse = UsbDevice::SetupResponse;
461
462 static constexpr uint8_t iad_descriptor_length() { return 8; }
463 static constexpr uint8_t interface_descriptor_length() { return 9; }
464 static constexpr uint8_t endpoint_descriptor_length() { return 7; }
465
466 static constexpr uint8_t m_endpoint_address_in() { return 1 << 7; }
467 static constexpr uint8_t m_endpoint_attributes_control() { return 0x00; }
468 static constexpr uint8_t m_endpoint_attributes_isochronous() { return 0x01; }
Brian Silvermanf71c3332017-11-23 20:38:22 -0500469 static constexpr uint8_t m_endpoint_attributes_bulk() { return 0x02; }
Brian Silvermanf91524f2017-09-23 13:15:55 -0400470 static constexpr uint8_t m_endpoint_attributes_interrupt() { return 0x03; }
471
472 // Adds a new endpoint and returns its index.
473 //
474 // Note that at least one descriptor for this newly created endpoint must be
475 // added via CreateConfigDescriptor.
476 //
477 // TODO(Brian): Does this hardware actually only support a single direction
478 // per endpoint number, or can it get a total of 30 endpoints max?
479 //
480 // May only be called during setup.
481 int AddEndpoint();
482
483 // Adds a new interface and returns its index.
484 //
485 // You'll probably want to put this new interface in at least one descriptor
486 // added via CreateConfigDescriptor.
487 //
488 // May only be called during setup.
489 int AddInterface();
490
491 // Adds a new descriptor in the configuration descriptor list. See
492 // UsbDescriptorList::CreateDescriptor for details.
493 //
494 // Note that the order of calls to this is highly significant. In general,
495 // this should only be called from Initialize().
496 //
497 // May only be called during setup.
498 template <typename T>
499 ::std::unique_ptr<UsbDescriptorList::Descriptor> CreateDescriptor(
500 uint8_t length, T descriptor_type) {
501 return device_->config_descriptor_list_.CreateDescriptor(length,
502 descriptor_type);
503 }
Brian Silvermand930f282017-11-04 23:09:12 -0400504 void AddPremadeDescriptor(const uint8_t *data, int length) {
505 device_->config_descriptor_list_.AddPremadeDescriptor(data, length);
506 }
Brian Silvermanf91524f2017-09-23 13:15:55 -0400507
508 UsbDevice *device() const { return device_; }
509
Brian Silverman4aa83042018-01-05 12:47:31 -0800510 void CreateIadDescriptor(int first_interface, int interface_count,
511 int function_class, int function_subclass,
512 int function_protocol,
513 const ::std::string &function);
514
515 // Sets the interface GUIDs for this function. Each GUID (one per interface?)
516 // should be followed by a NUL.
517 //
518 // If this is never called, no GUID extended property will be reported.
519 //
520 // This is needed to pass to Windows so WinUSB will be happy. Generate them at
521 // https://www.guidgenerator.com/online-guid-generator.aspx (Uppcase, Braces,
522 // and Hyphens).
523 //
524 // May only be called during setup.
525 void SetMicrosoftDeviceInterfaceGuids(const ::std::string &guids);
526
Brian Silvermanf91524f2017-09-23 13:15:55 -0400527 private:
528 virtual void Initialize() = 0;
529
530 virtual SetupResponse HandleEndpoint0SetupPacket(
531 const UsbDevice::SetupPacket & /*setup_packet*/) {
532 return SetupResponse::kIgnored;
533 }
534
535 virtual SetupResponse HandleEndpoint0OutPacket(void * /*data*/,
536 int /*data_length*/) {
537 return SetupResponse::kIgnored;
538 }
539
Brian Silvermand930f282017-11-04 23:09:12 -0400540 virtual SetupResponse HandleGetDescriptor(
541 const UsbDevice::SetupPacket & /*setup_packet*/) {
542 return SetupResponse::kIgnored;
543 }
544
Brian Silverman4aa83042018-01-05 12:47:31 -0800545 // Returns the concatenated compatible ID and subcompatible ID.
546 virtual ::std::string MicrosoftExtendedCompatibleId() {
547 // Default to both of them being "unused".
548 return ::std::string(16, '\0');
549 }
550
551 virtual void HandleOutFinished(int /*endpoint*/, BdtEntry * /*bdt_entry*/) {}
552 virtual void HandleInFinished(int /*endpoint*/, BdtEntry * /*bdt_entry*/,
553 EvenOdd /*odd*/) {}
Brian Silvermanf91524f2017-09-23 13:15:55 -0400554
555 // Called when a given interface is configured (aka "experiences a
556 // configuration event"). This means all rx and tx buffers have been cleared
557 // and should be filled as appropriate, starting from data0. Also,
558 // ConfigureEndpointFor should be called with the appropriate arguments.
559 virtual void HandleConfigured(int endpoint) = 0;
560
561 // Should reset everything to use the even buffers next.
562 virtual void HandleReset() = 0;
563
Brian Silverman4aa83042018-01-05 12:47:31 -0800564 int first_interface_ = -1;
565
566 // Filled out during Initialize().
567 ::std::string microsoft_extended_property_descriptor_;
568
Brian Silvermanf91524f2017-09-23 13:15:55 -0400569 UsbDevice *const device_;
570
571 friend class UsbDevice;
572};
573
574} // namespace teensy
575} // namespace frc971
576
577#endif // MOTORS_USB_USB_H_