-
Notifications
You must be signed in to change notification settings - Fork 270
/
usb.c
733 lines (604 loc) · 17.7 KB
/
usb.c
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
/* Copyright (c) 2011,2012 Simon Schubert <[email protected]>.
* Modifications by Jacob Alexander 2014-2020 <[email protected]>
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
// ----- Compiler Includes -----
#include <sys/types.h>
#include <inttypes.h>
#include <string.h>
// ----- Local Includes -----
#include "usb.h"
#include "usb-internal.h"
#include "dfu.desc.h"
#include "weak.h"
extern uint16_t udd_ctrl_prev_payload_nb_trans;
extern uint16_t udd_ctrl_payload_nb_trans;
// ----- Variables -----
#if defined(_kinetis_)
static uint8_t ep0_buf[2][EP0_BUFSIZE] __attribute__((aligned(4)));
struct usbd_t usb;
#elif defined(_sam_)
#include <stdbool.h>
typedef uint16_t le16_t;
typedef struct {
uint8_t bmRequestType;
uint8_t bRequest;
le16_t wValue;
le16_t wIndex;
le16_t wLength;
} usb_setup_req_t;
typedef struct {
//! Data received in USB SETUP packet
//! Note: The swap of "req.wValues" from uin16_t to le16_t is done by UDD.
usb_setup_req_t req;
//! Point to buffer to send or fill with data following SETUP packet
//! This buffer must be word align for DATA IN phase (use prefix COMPILER_WORD_ALIGNED for buffer)
uint8_t *payload;
//! Size of buffer to send or fill, and content the number of byte transfered
uint16_t payload_size;
//! Callback called after reception of ZLP from setup request
void (*callback) (void);
//! Callback called when the buffer given (.payload) is full or empty.
//! This one return false to abort data transfer, or true with a new buffer in .payload.
bool(*over_under_run) (void);
} udd_ctrl_request_t;
extern udd_ctrl_request_t udd_g_ctrlreq;
void udd_set_setup_payload( const uint8_t *payload, uint16_t payload_size );
#endif
// ----- Functions -----
// XXX
// UInt32 to Hex16 UTF16LE
// This function takes advantage of a few things to save on flash space
// 1) Does not set anything if zero
// 2) No padding
// 3) Starts from the LSD to avoid padding
void uint32ToHex16( uint32_t num, uint16_t* str )
{
for ( ; num; num /= 16 )
{
uint32_t cur = num % 16;
*--str = (uint16_t)( cur + (( cur < 10 ) ? '0' : 'A' - 10) );
}
}
#if defined(_kinetis_)
/**
* Returns: 0 when this is was the last transfer, 1 if there is still
* more to go.
*/
/* Defaults to EP0 for now */
static int usb_tx_next(struct usbd_ep_pipe_state_t *s)
{
/**
* Us being here means the previous transfer just completed
* successfully. That means the host just toggled its data
* sync bit, and so do we.
*/
s->data01 ^= 1;
if (s->transfer_size > 0) {
size_t thislen = s->transfer_size;
if (thislen > s->ep_maxsize)
thislen = s->ep_maxsize;
void *addr = s->data_buf + s->pos;
if (s->copy_source) {
/* Bounce buffer mode */
addr = s->data_buf;
memcpy(addr, s->copy_source + s->pos, thislen);
}
s->pos += thislen;
s->transfer_size -= thislen;
usb_queue_next(s, addr, thislen);
s->pingpong ^= 1;
return (1);
}
/**
* All data has been shipped. Do we need to send a short
* packet?
*/
if (s->short_transfer) {
s->short_transfer = 0;
usb_queue_next(s, NULL, 0);
s->pingpong ^= 1;
return (1);
}
if (s->callback)
s->callback(s->data_buf, s->pos, s->callback_data);
return (0);
}
static void setup_tx(struct usbd_ep_pipe_state_t *s, const void *buf, size_t len, size_t reqlen, ep_callback_t cb, void *cb_data)
{
s->data_buf = (void *)buf;
s->copy_source = NULL;
s->transfer_size = len;
s->pos = 0;
s->callback = cb;
s->callback_data = cb_data;
if (s->transfer_size > reqlen)
s->transfer_size = reqlen;
if (s->transfer_size < reqlen && s->transfer_size % s->ep_maxsize == 0)
s->short_transfer = 1;
else
s->short_transfer = 0;
}
static void submit_tx(struct usbd_ep_pipe_state_t *s)
{
/* usb_tx_next() flips the data toggle, so invert this here. */
s->data01 ^= 1;
usb_tx_next(s);
}
/**
* send USB data (IN device transaction)
*
* So far this function is specialized for EP 0 only.
*
* Returns: size to be transfered, or -1 on error.
*/
int usb_tx(struct usbd_ep_pipe_state_t *s, const void *buf, size_t len, size_t reqlen, ep_callback_t cb, void *cb_data)
{
setup_tx(s, buf, len, reqlen, cb, cb_data);
submit_tx(s);
return (s->transfer_size);
}
/**
* Returns: 0 when this is was the last transfer, 1 if there is still
* more to go.
*/
/* Defaults to EP0 for now */
/* XXX pass usb_stat to validate pingpong */
static int usb_rx_next(struct usbd_ep_pipe_state_t *s)
{
/**
* Us being here means the previous transfer just completed
* successfully. That means the host just toggled its data
* sync bit, and so do we.
*/
s->data01 ^= 1;
size_t thislen = usb_ep_get_transfer_size(s);
s->transfer_size -= thislen;
s->pos += thislen;
/**
* We're done with this buffer now. Switch the pingpong now
* before we might have to receive the next piece of data.
*/
s->pingpong ^= 1;
/**
* If this is a short transfer, or we received what we
* expected, we're done.
*/
if (thislen < s->ep_maxsize || s->transfer_size == 0) {
if (s->callback)
s->callback(s->data_buf, s->pos, s->callback_data);
return (0);
}
/**
* Otherwise we still need to receive more data.
*/
size_t nextlen = s->transfer_size;
if (nextlen > s->ep_maxsize)
nextlen = s->ep_maxsize;
void *addr = s->data_buf + s->pos;
usb_queue_next(s, addr, nextlen);
return (1);
}
/**
* Receive USB data (OUT device transaction)
*
* Returns: size to be received, or -1 on error.
*/
int usb_rx(struct usbd_ep_pipe_state_t *s, void *buf, size_t len, ep_callback_t cb, void *cb_data)
{
#if defined(_kinetis_)
s->data_buf = buf;
s->transfer_size = len;
s->pos = 0;
s->callback = cb;
s->callback_data = cb_data;
size_t thislen = s->transfer_size;
if (thislen > s->ep_maxsize)
thislen = s->ep_maxsize;
usb_queue_next(s, s->data_buf, thislen);
#elif defined(_sam_)
#endif
return (len);
}
int usb_ep0_tx_cp(const void *buf, size_t len, size_t reqlen, ep_callback_t cb, void *cb_data)
{
struct usbd_ep_pipe_state_t *s = &usb.ep_state[0].tx;
enum usb_ep_pingpong pp = s->pingpong;
setup_tx(s, ep0_buf[pp], len, reqlen, cb, cb_data);
s->copy_source = buf;
submit_tx(s);
return (s->transfer_size);
}
void *usb_ep0_tx_inplace_prepare(size_t len)
{
enum usb_ep_pingpong pp = usb.ep_state[0].tx.pingpong;
if (len > EP0_BUFSIZE)
return (NULL);
return (ep0_buf[pp]);
}
int usb_ep0_tx(void *buf, size_t len, size_t reqlen, ep_callback_t cb, void *cb_data)
{
return (usb_tx(&usb.ep_state[0].tx, buf, len, reqlen, cb, cb_data));
}
int usb_ep0_rx(void *buf, size_t len, ep_callback_t cb, void *cb_data)
{
return (usb_rx(&usb.ep_state[0].rx, buf, len, cb, cb_data));
}
const struct usbd_config *
usb_get_config_data(int config)
{
if (config <= 0)
config = usb.config;
if (config != 0)
return (usb.identity->configs[config - 1]);
else
return (NULL);
}
static int usb_set_config(int config)
{
const struct usbd_config *config_data;
if (usb.config != 0) {
config_data = usb_get_config_data(-1);
if (config_data != NULL && config_data->init != NULL)
config_data->init(0);
}
if (config != 0) {
/* XXX overflow */
config_data = usb_get_config_data(config);
if (config_data != NULL && config_data->init != NULL)
config_data->init(1);
}
usb.config = config;
return (0);
}
static int usb_set_interface(int iface, int altsetting)
{
int iface_count = 0;
for (struct usbd_function_ctx_header *fh = &usb.functions;
fh != NULL;
fh = fh->next, iface_count += fh->function->interface_count) {
if (iface - iface_count < fh->function->interface_count) {
if (fh->function->configure != NULL)
return (fh->function->configure(iface,
iface - iface_count,
altsetting,
fh));
/* Default to a single altsetting */
if (altsetting != 0)
return (-1);
else
return (0);
}
}
return (-1);
}
static int usb_tx_config_desc(int idx, int reqlen)
{
const struct usb_desc_config_t *d = usb.identity->configs[idx]->desc;
usb_ep0_tx_cp(d, d->wTotalLength, reqlen, NULL, NULL);
return (0);
}
static int usb_tx_string_desc(int idx, int reqlen)
{
struct usb_desc_string_t * const *d;
// Microsoft looks for a special string at index 0xEE
// If found it will be compared against known OS compatabilily strings
// Once matched additional Microsoft-specific setup requests may be sent
if (idx == 0xEE) {
d = (struct usb_desc_string_t* const *)&msft_extended_compat_desc;
usb_ep0_tx_cp(*d, (*d)->bLength, reqlen, NULL, NULL);
return (0);
}
for (d = usb.identity->string_descs; idx != 0 && *d != NULL; ++d)
--idx;
switch ((uintptr_t)*d) {
case (uintptr_t)NULL:
return (-1);
case (uintptr_t)USB_DESC_STRING_SERIALNO:
return (usb_tx_serialno(reqlen));
default:
usb_ep0_tx_cp(*d, (*d)->bLength, reqlen, NULL, NULL);
return (0);
}
}
static void usb_handle_control_done(void *data, ssize_t len, void *cbdata)
{
if (usb.state == USBD_STATE_SETTING_ADDRESS) {
usb.state = USBD_STATE_ADDRESS;
usb_set_addr(usb.address);
}
usb_setup_control();
}
void usb_handle_control_status_cb(ep_callback_t cb)
{
/* empty status transfer */
switch (usb.ctrl_dir) {
case USB_CTRL_REQ_IN:
usb.ep_state[0].rx.data01 = USB_DATA01_DATA1;
usb_rx(&usb.ep_state[0].rx, NULL, 0, cb, NULL);
break;
default:
usb.ep_state[0].tx.data01 = USB_DATA01_DATA1;
usb_ep0_tx_cp(NULL, 0, 1 /* short packet */, cb, NULL);
break;
}
}
void usb_handle_control_status(int fail)
{
if (fail) {
usb_pipe_stall(&usb.ep_state[0].rx);
usb_pipe_stall(&usb.ep_state[0].tx);
} else {
usb_handle_control_status_cb(usb_handle_control_done);
}
}
/**
* Dispatch non-standard request to registered USB functions.
*/
static void usb_handle_control_nonstd(struct usb_ctrl_req_t *req)
{
/* XXX filter by interface/endpoint? */
for (struct usbd_function_ctx_header *fh = &usb.functions; fh != NULL; fh = fh->next) {
/* ->control() returns != 0 if it handled the request */
if (fh->function->control != NULL &&
fh->function->control(req, fh))
return;
}
usb_handle_control_status(-1);
}
/**
*
* Great resource: http://wiki.osdev.org/Universal_Serial_Bus
*
* Control Transfers
* -----------------
*
* A control transfer consists of a SETUP transaction (1), zero or
* more data transactions (IN or OUT) (2), and a final status
* transaction (3).
*
* Token sequence (data toggle):
* 1. SETUP (0)
* (2a. OUT (1) ... (toggling))
* 3a. IN (1)
*
* or
* 1. SETUP (0)
* 2b. IN (1) ... (toggling)
* 3b. OUT (1)
*
* Report errors by STALLing the control EP after (1) or (2), so that
* (3) will STALL. Seems we need to clear the STALL after that so
* that the next SETUP can make it through.
*
*
*/
/**
* The following code is not written defensively, but instead only
* asserts values that are essential for correct execution. It
* accepts a superset of the protocol defined by the standard. We do
* this to save space.
*/
static void usb_handle_control(void *data, ssize_t len, void *cbdata)
{
struct usb_ctrl_req_t *req = data;
uint16_t zero16 = 0;
int fail = 1;
usb.ctrl_dir = req->in;
if (req->type != USB_CTRL_REQ_STD) {
usb_handle_control_nonstd(req);
return;
}
/* Only STD requests here */
switch (req->bRequest) {
case USB_CTRL_REQ_GET_STATUS:
/**
* Because we don't support remote wakeup or
* self-powered operation, and we are specialized to
* only EP 0 so far, all GET_STATUS replies are just
* empty.
*/
usb_ep0_tx_cp(&zero16, sizeof(zero16), req->wLength, NULL, NULL);
break;
case USB_CTRL_REQ_CLEAR_FEATURE:
case USB_CTRL_REQ_SET_FEATURE:
/**
* Nothing to do. Maybe return STALLs on illegal
* accesses?
*/
break;
case USB_CTRL_REQ_SET_ADDRESS:
/**
* We must keep our previous address until the end of
* the status stage; therefore we can't set the
* address right now. Since this is a special case,
* the EP 0 handler will take care of this later on.
*/
usb.address = req->wValue & 0x7f;
usb.state = USBD_STATE_SETTING_ADDRESS;
break;
case USB_CTRL_REQ_GET_DESCRIPTOR:
switch (req->wValue >> 8) {
case USB_DESC_DEV:
usb_ep0_tx_cp(usb.identity->dev_desc, usb.identity->dev_desc->bLength,
req->wLength, NULL, NULL);
fail = 0;
break;
case USB_DESC_CONFIG:
fail = usb_tx_config_desc(req->wValue & 0xff, req->wLength);
break;
case USB_DESC_STRING:
fail = usb_tx_string_desc(req->wValue & 0xff, req->wLength);
break;
default:
fail = -1;
break;
// Cleanup lsusb errors, just return 0 instead of stalling
case USB_DESC_DEVQUAL:
case USB_DESC_DEBUG:
usb_ep0_tx_cp(&zero16, sizeof(zero16), req->wLength, NULL, NULL);
fail = 0;
break;
}
/* we set fail already, so we can go directly to `err' */
goto err;
case USB_CTRL_REQ_GET_CONFIGURATION:
usb_ep0_tx_cp(&usb.config, 1, req->wLength, NULL, NULL); /* XXX implicit LE */
break;
case USB_CTRL_REQ_SET_CONFIGURATION:
if (usb_set_config(req->wValue) < 0)
goto err;
break;
case USB_CTRL_REQ_GET_INTERFACE:
/* We only support iface setting 0 */
usb_ep0_tx_cp(&zero16, 1, req->wLength, NULL, NULL);
break;
case USB_CTRL_REQ_SET_INTERFACE:
if (usb_set_interface(req->wIndex, req->wValue) < 0)
goto err;
break;
default:
goto err;
}
fail = 0;
err:
usb_handle_control_status(fail);
}
void usb_setup_control(void)
{
void *buf = ep0_buf[usb.ep_state[0].rx.pingpong];
usb.ep_state[0].rx.data01 = USB_DATA01_DATA0;
usb.ep_state[0].tx.data01 = USB_DATA01_DATA1;
usb_rx(&usb.ep_state[0].rx, buf, EP0_BUFSIZE, usb_handle_control, NULL);
}
/**
* This is called by the interrupt handler
*/
void usb_handle_transaction(struct usb_xfer_info *info)
{
enum usb_tok_pid pid = usb_get_xfer_pid(info);
struct usbd_ep_state_t *eps = &usb.ep_state[usb_get_xfer_ep(info)];
struct usbd_ep_pipe_state_t *s = &eps->pipe[usb_get_xfer_dir(info)];
switch (pid) {
case USB_PID_SETUP:
case USB_PID_OUT:
/**
* If we receive a SETUP transaction, but don't expect
* it (callback set to somewhere else), stall the EP.
*/
if (pid == USB_PID_SETUP && s->callback != usb_handle_control)
usb_handle_control_status(1);
else
usb_rx_next(s);
if (pid == USB_PID_SETUP)
usb_enable_xfers();
break;
case USB_PID_IN:
usb_tx_next(s);
break;
default:
break;
}
}
struct usbd_ep_pipe_state_t *usb_init_ep(struct usbd_function_ctx_header *ctx, int ep, enum usb_ep_dir dir, size_t size)
{
struct usbd_ep_pipe_state_t *s;
if (dir == USB_EP_RX)
s = &usb.ep_state[ctx->ep_rx_offset + ep].rx;
else
s = &usb.ep_state[ctx->ep_tx_offset + ep].tx;
memset(s, 0, sizeof(*s));
s->ep_maxsize = size;
s->ep_num = ep;
s->ep_dir = dir;
usb_pipe_enable(s);
return (s);
}
void usb_restart(void)
{
const struct usbd_device *identity = usb.identity;
/* XXX reset existing functions? */
memset(&usb, 0, sizeof(usb));
usb.functions.function = &usb.control_function;
usb.identity = identity;
usb_init_ep(&usb.functions, 0, USB_EP_RX, EP0_BUFSIZE);
usb_init_ep(&usb.functions, 0, USB_EP_TX, EP0_BUFSIZE);
usb_setup_control();
}
void usb_attach_function(const struct usbd_function *function, struct usbd_function_ctx_header *ctx)
{
/* XXX right now this requires a sequential initialization */
struct usbd_function_ctx_header *prev = &usb.functions;
while (prev->next != NULL)
prev = prev->next;
ctx->next = NULL;
ctx->function = function;
ctx->interface_offset = prev->interface_offset + prev->function->interface_count;
ctx->ep_rx_offset = prev->ep_rx_offset + prev->function->ep_rx_count;
ctx->ep_tx_offset = prev->ep_tx_offset + prev->function->ep_tx_count;
prev->next = ctx;
}
#elif defined(_sam_)
static ep_callback_t _cb_func;
static void *_cb_data;
bool cb_wrapper() {
_cb_func(udd_g_ctrlreq.payload, udd_ctrl_payload_nb_trans, _cb_data);
return true;
}
void udd_set_setup_callback(ep_callback_t cb, void *cb_data) {
_cb_func = cb;
_cb_data = cb_data;
udd_g_ctrlreq.over_under_run = cb_wrapper;
}
int usb_ep0_tx(void *buf, size_t len, size_t reqlen, ep_callback_t cb, void *cb_data) {
if (len > reqlen)
len = reqlen;
udd_set_setup_payload(buf, len);
udd_set_setup_callback(cb, cb_data);
return udd_ctrl_payload_nb_trans - udd_ctrl_prev_payload_nb_trans;
}
int usb_ep0_rx(void *buf, size_t len, ep_callback_t cb, void *cb_data) {
udd_set_setup_payload(buf, len);
udd_set_setup_callback(cb, cb_data);
return udd_ctrl_payload_nb_trans - udd_ctrl_prev_payload_nb_trans;
}
int usb_ep0_tx_cp(const void *buf, size_t len, size_t reqlen, ep_callback_t cb, void *cb_data) {
if (len > reqlen)
len = reqlen;
udd_set_setup_payload(buf, len);
udd_set_setup_callback(cb, cb_data);
return udd_ctrl_payload_nb_trans - udd_ctrl_prev_payload_nb_trans;
}
void usb_handle_control_status_cb(ep_callback_t cb) {
udd_g_ctrlreq.callback = (void (*)(void))cb;
}
void usb_attach_function(const struct usbd_function *function, struct usbd_function_ctx_header *ctx) {}
void usb_handle_control_status(int fail) {}
#endif
void usb_init(const struct usbd_device *identity)
{
// Set the device serial number to the reserved iSerial string memory
#if defined(_kinetis_)
uint32ToHex16( SIM_UIDH, &(dfu_device_str_desc[3]->bString[8]) );
uint32ToHex16( SIM_UIDMH, &(dfu_device_str_desc[3]->bString[16]) );
uint32ToHex16( SIM_UIDML, &(dfu_device_str_desc[3]->bString[24]) );
uint32ToHex16( SIM_UIDL, &(dfu_device_str_desc[3]->bString[32]) );
usb.identity = identity;
usb_enable();
#elif defined(_sam_)
Chip_serial_number_setup();
init_usb_bootloader(0);
#endif
}