blob: 4db29dc6ff79904846ae9bbfb1057a6e974fb689 [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 Silvermand930f282017-11-04 23:09:12 -0400109// The HID class specification says this. Can't find any mention in the main
110// standard.
111#define G_DESCRIPTOR_TYPE_TYPE(descriptor_type) \
112 ((descriptor_type) >> 5 & UINT8_C(3))
113namespace standard_descriptor_type_types {
114constexpr int kStandard = 0;
115constexpr int kClass = 1;
116constexpr int kVendor = 2;
117} // namespace standard_descriptor_type_types
118
Brian Silvermanf91524f2017-09-23 13:15:55 -0400119class UsbFunction;
120
121// Allows building up a list of descriptors. This supports a much nicer API than
122// the usual "hard-code a char[] with all the sizes and offsets at compile
123// time". Space for each descriptor is reserved, and then it may be filled out
124// from beginning to end at any time.
125//
126// An instance is the thing that the GetDescriptor operation sends to the host.
127// This is not the concept that the core and class standards call "Foo
128// Descriptor" etc; see Descriptor for that.
129class UsbDescriptorList {
130 public:
131 // Represents a single descriptor. All of the contents must be written before
132 // this object is destroyed.
133 //
134 // Create one via UsbDescriptorList::CreateDescriptor.
135 class Descriptor {
136 public:
137 // All of the allocated space must be filled first.
138 ~Descriptor() {
139 if (descriptor_list_ == nullptr) {
140 return;
141 }
142 // Verify we wrote all the bytes first.
143 assert(next_index_ == end_index_);
144 --descriptor_list_->open_descriptors_;
145 }
146
147 void AddUint16(uint16_t value) {
148 AddByte(value & 0xFF);
149 AddByte((value >> 8) & 0xFF);
150 }
151
152 void AddByte(uint8_t value) {
153 assert(next_index_ < end_index_);
154 data()[next_index_] = value;
155 ++next_index_;
156 }
157
158 // Overwrites an already-written byte.
159 void SetByte(int index, uint8_t value) {
160 assert(index + start_index_ < end_index_);
161 data()[index + start_index_] = value;
162 }
163
164 private:
165 Descriptor(UsbDescriptorList *descriptor_list, int start_index,
166 int end_index)
167 : descriptor_list_(descriptor_list),
168 start_index_(start_index),
169 end_index_(end_index),
170 next_index_(start_index_) {}
171
172 char *data() const {
173 return &descriptor_list_->data_[0];
174 }
175
176 UsbDescriptorList *const descriptor_list_;
177 const int start_index_, end_index_;
178 int next_index_;
179
180 friend class UsbDescriptorList;
181
182 DISALLOW_COPY_AND_ASSIGN(Descriptor);
183 };
184
185 UsbDescriptorList() = default;
186 ~UsbDescriptorList() = default;
187
188 // Creates a new descriptor at the end of the list.
189 // length is the number of bytes, including the length byte.
190 // descriptor_type is the descriptor type, which is the second byte after the
191 // length.
192 ::std::unique_ptr<Descriptor> CreateDescriptor(
193 uint8_t length, UsbDescriptorType descriptor_type) {
194 return CreateDescriptor(length, static_cast<uint8_t>(descriptor_type));
195 }
196
197 ::std::unique_ptr<Descriptor> CreateDescriptor(
198 uint8_t length, UsbClassDescriptorType descriptor_type) {
199 assert(data_.size() > 0);
200 return CreateDescriptor(length, static_cast<uint8_t>(descriptor_type));
201 }
202
Brian Silvermand930f282017-11-04 23:09:12 -0400203 void AddPremadeDescriptor(const uint8_t *data, int length) {
204 const int start_index = data_.size();
205 const int end_index = start_index + length;
206 data_.resize(end_index);
207 memcpy(&data_[start_index], data, length);
208 }
209
Brian Silvermanf91524f2017-09-23 13:15:55 -0400210 void CheckFinished() const { assert(open_descriptors_ == 0); }
211
212 int CurrentSize() const { return data_.size(); }
213
214 private:
215 ::std::unique_ptr<Descriptor> CreateDescriptor(uint8_t length,
216 uint8_t descriptor_type) {
217 const int start_index = data_.size();
218 const int end_index = start_index + length;
219 data_.resize(end_index);
220 ++open_descriptors_;
221 auto r = ::std::unique_ptr<Descriptor>(
222 new Descriptor(this, start_index, end_index));
223 r->AddByte(length); // bLength
224 r->AddByte(descriptor_type); // bDescriptorType
225 return r;
226 }
227
228 int open_descriptors_ = 0;
229
230 ::std::string data_;
231
232 friend class UsbDevice;
233
234 DISALLOW_COPY_AND_ASSIGN(UsbDescriptorList);
235};
236
237extern "C" void usb_isr(void);
238
239// USB state events are managed by asking each function if it wants to handle
240// them, sequentially. For the small number of functions which can be
241// practically supported with the limited number of endpoints, this performs
242// better than fancier things like hash maps.
243
244// Manages one of the Teensy's USB peripherals as a USB slave device.
245//
246// This supports being a composite device with multiple functions.
247//
248// Attaching functions etc is called "setup", and must be completed before
249// Initialize() is called.
250//
251// Detaching functions is called "teardown" and must happen after Shutdown().
252// TODO(Brian): Implement Shutdown().
253class UsbDevice final {
254 public:
255 // Represents the data that comes with a UsbPid::kSetup.
256 // Note that the order etc is important because we memcpy into this.
257 struct SetupPacket {
258 uint8_t request_type; // bmRequestType
259 uint8_t request; // bRequest
260 uint16_t value; // wValue
261 uint16_t index; // wIndex
262 uint16_t length; // wLength
263 } __attribute__((aligned(4)));
264 static_assert(sizeof(SetupPacket) == 8, "wrong size");
265
266 enum class SetupResponse {
267 // Indicates this function doesn't recognize the setup packet.
268 kIgnored,
269
270 // Indicates the endpoint should be stalled.
271 //
272 // Don't return this if the packet is for another function.
273 kStall,
274
275 // Indicates this setup packet was handled. Functions must avoid eating
276 // packets intended for other functions.
277 kHandled,
278 };
279
280 static constexpr int kEndpoint0MaxSize = 64;
281
282 // The only language code we support.
283 static constexpr uint16_t english_us_code() { return 0x0409; }
284
285 UsbDevice(int index, uint16_t vendor_id, uint16_t product_id);
286 ~UsbDevice();
287
288 // Ends setup and starts being an actual USB device.
289 void Initialize();
290
291 // Adds a string to the table and returns its index.
292 //
293 // For simplicity, we only support strings with english_us_code().
294 //
295 // May only be called during setup.
296 int AddString(const ::std::string &string) {
297 assert(!is_set_up_);
298 const int r = strings_.size();
299 strings_.emplace_back(string.size() * 2 + 2, '\0');
300 strings_.back()[0] = 2 + string.size() * 2;
301 strings_.back()[1] = static_cast<uint8_t>(UsbDescriptorType::kString);
302 for (size_t i = 0; i < string.size(); ++i) {
303 strings_.back()[i * 2 + 2] = string[i];
304 }
305 return r;
306 }
307
308 // Sets the manufacturer string.
309 //
310 // May only be called during setup.
311 void SetManufacturer(const ::std::string &string) {
312 device_descriptor_->SetByte(14, AddString(string)); // iManufacturer
313 }
314
315 // Sets the product string.
316 //
317 // May only be called during setup.
318 void SetProduct(const ::std::string &string) {
319 device_descriptor_->SetByte(15, AddString(string)); // iProduct
320 }
321
322 // Sets the serial number string.
323 //
324 // May only be called during setup.
325 void SetSerialNumber(const ::std::string &string) {
326 device_descriptor_->SetByte(16, AddString(string)); // iSerialNumber
327 }
328
329 // Queues up an empty IN packet for endpoint 0. This is a common way to
330 // respond to various kinds of configuration commands.
331 //
332 // This may only be called from the appropriate function callbacks.
333 void SendEmptyEndpoint0Packet();
334
335 // Queues some data to send on endpoint 0. This includes putting the initial
336 // packets into the TX buffers.
337 //
338 // This may only be called from the appropriate function callbacks.
339 void QueueEndpoint0Data(const char *data, int size);
340
341 // Stalls an endpoint until it's cleared.
342 //
343 // This should only be called by or on behalf of the function which owns
344 // endpoint.
345 void StallEndpoint(int endpoint);
346
347 // Configures an endpoint to send and/or receive, with or without DATA0/DATA1
348 // handshaking. handshake should probably be true for everything except
349 // isochronous endpoints.
350 //
351 // This should only be called by or on behalf of the function which owns
352 // endpoint.
353 void ConfigureEndpointFor(int endpoint, bool rx, bool tx, bool handshake);
354
355 void SetBdtEntry(int endpoint, Direction direction, EvenOdd odd,
356 BdtEntry bdt_entry);
357
358 private:
359 // Clears all pending interrupts.
360 void ClearInterrupts();
361
362 // Deals with an interrupt that has occured.
363 void HandleInterrupt();
364
365 // Processes a token on endpoint 0.
366 void HandleEndpoint0Token(uint8_t stat);
367
368 // Processes a setup packet on endpoint 0.
369 void HandleEndpoint0SetupPacket(const SetupPacket &setup_packet);
370
371 // Sets endpoint 0 to return STALL tokens. We clear this condition upon
372 // receiving the next SETUP token.
373 void StallEndpoint0();
374
375 // Places the first packet from {endpoint0_data_, endpoint0_data_left_} into
376 // the TX buffers (if there is any data). This may only be called when the
377 // next TX buffer is empty.
378 bool BufferEndpoint0TxPacket();
379
380 // Which USB peripheral this is.
381 const int index_;
382
383 // The string descriptors in order.
384 ::std::vector<::std::string> strings_;
385
386 // TODO(Brian): Refactor into something more generic, because I think this is
387 // shared with all non-isochronous endpoints?
388 Data01 endpoint0_tx_toggle_;
389 EvenOdd endpoint0_tx_odd_;
390 uint8_t endpoint0_receive_buffer_[2][kEndpoint0MaxSize]
391 __attribute__((aligned(4)));
392
393 // A temporary buffer for holding data to transmit on endpoint 0. Sometimes
394 // this is used and sometimes the data is sent directly from some other
395 // location (like for descriptors).
396 char endpoint0_transmit_buffer_[kEndpoint0MaxSize];
397
398 // The data we're waiting to send from endpoint 0. The data must remain
399 // constant until this transmission is done.
400 //
401 // When overwriting this, we ignore if it's already non-nullptr. The host is
402 // supposed to read all of the data before asking for more. If it doesn't do
403 // that, it will just get garbage data because it's unclear what it expects.
404 //
405 // Do note that endpoint0_data_ != nullptr && endpoint0_data_left_ == 0 is an
406 // important state. This means we're going to return a 0-length packet the
407 // next time the host asks. However, depending on the length it asked for,
408 // that might never happen.
409 const char *endpoint0_data_ = nullptr;
410 int endpoint0_data_left_ = 0;
411
412 // If non-0, the new address we're going to start using once the status stage
413 // of the current setup request is finished.
414 uint16_t new_address_ = 0;
415
416 UsbDescriptorList device_descriptor_list_;
417 UsbDescriptorList config_descriptor_list_;
418
419 ::std::unique_ptr<UsbDescriptorList::Descriptor> device_descriptor_,
420 config_descriptor_;
421
422 int configuration_ = 0;
423
424 bool is_set_up_ = false;
425
426 // The function which owns each endpoint.
427 ::std::vector<UsbFunction *> endpoint_mapping_;
428 // The function which owns each interface.
429 ::std::vector<UsbFunction *> interface_mapping_;
430 // All of the functions (without duplicates).
431 ::std::vector<UsbFunction *> functions_;
432
433 friend void usb_isr(void);
434 friend class UsbFunction;
435};
436
437// Represents a USB function. This consists of a set of descriptors and
438// interfaces.
439//
440// Each instance is a single function, so there can be multiple instances of the
441// same subclass in the same devices (ie two serial ports).
442class UsbFunction {
443 public:
444 UsbFunction(UsbDevice *device) : device_(device) {
445 device_->functions_.push_back(this);
446 }
447 virtual ~UsbFunction() = default;
448
449 protected:
450 using SetupResponse = UsbDevice::SetupResponse;
451
452 static constexpr uint8_t iad_descriptor_length() { return 8; }
453 static constexpr uint8_t interface_descriptor_length() { return 9; }
454 static constexpr uint8_t endpoint_descriptor_length() { return 7; }
455
456 static constexpr uint8_t m_endpoint_address_in() { return 1 << 7; }
457 static constexpr uint8_t m_endpoint_attributes_control() { return 0x00; }
458 static constexpr uint8_t m_endpoint_attributes_isochronous() { return 0x01; }
Brian Silvermanf71c3332017-11-23 20:38:22 -0500459 static constexpr uint8_t m_endpoint_attributes_bulk() { return 0x02; }
Brian Silvermanf91524f2017-09-23 13:15:55 -0400460 static constexpr uint8_t m_endpoint_attributes_interrupt() { return 0x03; }
461
462 // Adds a new endpoint and returns its index.
463 //
464 // Note that at least one descriptor for this newly created endpoint must be
465 // added via CreateConfigDescriptor.
466 //
467 // TODO(Brian): Does this hardware actually only support a single direction
468 // per endpoint number, or can it get a total of 30 endpoints max?
469 //
470 // May only be called during setup.
471 int AddEndpoint();
472
473 // Adds a new interface and returns its index.
474 //
475 // You'll probably want to put this new interface in at least one descriptor
476 // added via CreateConfigDescriptor.
477 //
478 // May only be called during setup.
479 int AddInterface();
480
481 // Adds a new descriptor in the configuration descriptor list. See
482 // UsbDescriptorList::CreateDescriptor for details.
483 //
484 // Note that the order of calls to this is highly significant. In general,
485 // this should only be called from Initialize().
486 //
487 // May only be called during setup.
488 template <typename T>
489 ::std::unique_ptr<UsbDescriptorList::Descriptor> CreateDescriptor(
490 uint8_t length, T descriptor_type) {
491 return device_->config_descriptor_list_.CreateDescriptor(length,
492 descriptor_type);
493 }
Brian Silvermand930f282017-11-04 23:09:12 -0400494 void AddPremadeDescriptor(const uint8_t *data, int length) {
495 device_->config_descriptor_list_.AddPremadeDescriptor(data, length);
496 }
Brian Silvermanf91524f2017-09-23 13:15:55 -0400497
498 UsbDevice *device() const { return device_; }
499
500 private:
501 virtual void Initialize() = 0;
502
503 virtual SetupResponse HandleEndpoint0SetupPacket(
504 const UsbDevice::SetupPacket & /*setup_packet*/) {
505 return SetupResponse::kIgnored;
506 }
507
508 virtual SetupResponse HandleEndpoint0OutPacket(void * /*data*/,
509 int /*data_length*/) {
510 return SetupResponse::kIgnored;
511 }
512
Brian Silvermand930f282017-11-04 23:09:12 -0400513 virtual SetupResponse HandleGetDescriptor(
514 const UsbDevice::SetupPacket & /*setup_packet*/) {
515 return SetupResponse::kIgnored;
516 }
517
Brian Silvermanf91524f2017-09-23 13:15:55 -0400518 virtual void HandleOutFinished(int endpoint, BdtEntry *bdt_entry) = 0;
519 virtual void HandleInFinished(int endpoint, BdtEntry *bdt_entry,
520 EvenOdd odd) = 0;
521
522 // Called when a given interface is configured (aka "experiences a
523 // configuration event"). This means all rx and tx buffers have been cleared
524 // and should be filled as appropriate, starting from data0. Also,
525 // ConfigureEndpointFor should be called with the appropriate arguments.
526 virtual void HandleConfigured(int endpoint) = 0;
527
528 // Should reset everything to use the even buffers next.
529 virtual void HandleReset() = 0;
530
531 UsbDevice *const device_;
532
533 friend class UsbDevice;
534};
535
536} // namespace teensy
537} // namespace frc971
538
539#endif // MOTORS_USB_USB_H_