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