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