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