A modern Music Player Daemon based on Rockbox open source high quality audio player
libadwaita
audio
rust
zig
deno
mpris
rockbox
mpd
1/***************************************************************************
2 * __________ __ ___.
3 * Open \______ \ ____ ____ | | _\_ |__ _______ ___
4 * Source | _// _ \_/ ___\| |/ /| __ \ / _ \ \/ /
5 * Jukebox | | ( <_> ) \___| < | \_\ ( <_> > < <
6 * Firmware |____|_ /\____/ \___ >__|_ \|___ /\____/__/\_ \
7 * \/ \/ \/ \/ \/
8 * $Id$
9 *
10 * Copyright (C) 2007 by Björn Stenberg
11 *
12 * This program is free software; you can redistribute it and/or
13 * modify it under the terms of the GNU General Public License
14 * as published by the Free Software Foundation; either version 2
15 * of the License, or (at your option) any later version.
16 *
17 * This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY
18 * KIND, either express or implied.
19 *
20 ****************************************************************************/
21#include "system.h"
22#include "thread.h"
23#include "kernel.h"
24#include "string.h"
25#include "panic.h"
26/*#define LOGF_ENABLE*/
27#include "logf.h"
28
29#include "usb.h"
30#include "usb_ch9.h"
31#include "usb_drv.h"
32#include "usb_core.h"
33#include "usb_class_driver.h"
34
35#if defined(USB_ENABLE_STORAGE)
36#include "usb_storage.h"
37#endif
38
39#if defined(USB_ENABLE_SERIAL)
40#include "usb_serial.h"
41#endif
42
43#if defined(USB_ENABLE_CHARGING_ONLY)
44#include "usb_charging_only.h"
45#endif
46
47#ifdef USB_ENABLE_HID
48#include "usb_hid.h"
49#endif
50
51#ifdef USB_ENABLE_AUDIO
52#include "usb_audio.h"
53#include "usb_audio_def.h" // DEBUG
54#endif
55
56/* TODO: Move target-specific stuff somewhere else (serial number reading) */
57
58#if defined(IPOD_ARCH) && defined(CPU_PP)
59// no need to include anything
60#elif defined(HAVE_AS3514)
61#include "ascodec.h"
62#include "as3514.h"
63#elif (CONFIG_CPU == IMX233) && IMX233_SUBTARGET >= 3700
64#include "ocotp-imx233.h"
65#elif defined(SANSA_CONNECT)
66#include "cryptomem-sansaconnect.h"
67#elif (CONFIG_STORAGE & STORAGE_ATA)
68#include "ata.h"
69#endif
70
71#ifndef USB_MAX_CURRENT
72#define USB_MAX_CURRENT 500
73#endif
74
75/*-------------------------------------------------------------------------*/
76/* USB protocol descriptors: */
77
78static struct usb_device_descriptor __attribute__((aligned(2)))
79 device_descriptor=
80{
81 .bLength = sizeof(struct usb_device_descriptor),
82 .bDescriptorType = USB_DT_DEVICE,
83#ifndef USB_NO_HIGH_SPEED
84 .bcdUSB = 0x0200,
85#else
86 .bcdUSB = 0x0110,
87#endif
88 .bDeviceClass = USB_CLASS_PER_INTERFACE,
89 .bDeviceSubClass = 0,
90 .bDeviceProtocol = 0,
91 .bMaxPacketSize0 = 64,
92 .idVendor = USB_VENDOR_ID,
93 .idProduct = USB_PRODUCT_ID,
94 .bcdDevice = 0x0100,
95 .iManufacturer = USB_STRING_INDEX_MANUFACTURER,
96 .iProduct = USB_STRING_INDEX_PRODUCT,
97 .iSerialNumber = USB_STRING_INDEX_SERIAL,
98 .bNumConfigurations = 1
99} ;
100
101static struct usb_config_descriptor __attribute__((aligned(2)))
102 config_descriptor =
103{
104 .bLength = sizeof(struct usb_config_descriptor),
105 .bDescriptorType = USB_DT_CONFIG,
106 .wTotalLength = 0, /* will be filled in later */
107 .bNumInterfaces = 1,
108 .bConfigurationValue = 1,
109 .iConfiguration = 0,
110 .bmAttributes = USB_CONFIG_ATT_ONE | USB_CONFIG_ATT_SELFPOWER,
111 .bMaxPower = (USB_MAX_CURRENT + 1) / 2, /* In 2mA units */
112};
113
114static const struct usb_qualifier_descriptor __attribute__((aligned(2)))
115 qualifier_descriptor =
116{
117 .bLength = sizeof(struct usb_qualifier_descriptor),
118 .bDescriptorType = USB_DT_DEVICE_QUALIFIER,
119 .bcdUSB = 0x0200,
120 .bDeviceClass = 0,
121 .bDeviceSubClass = 0,
122 .bDeviceProtocol = 0,
123 .bMaxPacketSize0 = 64,
124 .bNumConfigurations = 1
125};
126
127static const struct usb_string_descriptor usb_string_iManufacturer =
128USB_STRING_INITIALIZER(u"Rockbox.org");
129
130static const struct usb_string_descriptor usb_string_iProduct =
131USB_STRING_INITIALIZER(u"Rockbox media player");
132
133static struct usb_string_descriptor usb_string_iSerial =
134USB_STRING_INITIALIZER(u"00000000000000000000000000000000000000000");
135
136/* Generic for all targets */
137
138/* this is stringid #0: languages supported */
139static const struct usb_string_descriptor __attribute__((aligned(2)))
140 lang_descriptor =
141USB_STRING_INITIALIZER(u"\x0409"); /* LANGID US English */
142
143static const struct usb_string_descriptor* const usb_strings[USB_STRING_INDEX_MAX] =
144{
145 [USB_STRING_INDEX_LANGUAGE] = &lang_descriptor,
146 [USB_STRING_INDEX_MANUFACTURER] = &usb_string_iManufacturer,
147 [USB_STRING_INDEX_PRODUCT] = &usb_string_iProduct,
148 [USB_STRING_INDEX_SERIAL] = &usb_string_iSerial,
149};
150
151static int usb_address = 0;
152static bool initialized = false;
153static bool drivers_connected = false;
154static enum { DEFAULT, ADDRESS, CONFIGURED } usb_state;
155
156#ifdef HAVE_USB_CHARGING_ENABLE
157static int usb_charging_mode = USB_CHARGING_DISABLE;
158static int usb_charging_current_requested = 500;
159static struct timeout usb_no_host_timeout;
160static bool usb_no_host = false;
161
162static int usb_no_host_callback(struct timeout *tmo)
163{
164 (void)tmo;
165 usb_no_host = true;
166 usb_charger_update();
167 return 0;
168}
169#endif
170
171static int usb_core_num_interfaces;
172
173typedef void (*completion_handler_t)(int ep, int dir, int status, int length);
174typedef bool (*fast_completion_handler_t)(int ep, int dir, int status, int length);
175typedef bool (*control_handler_t)(struct usb_ctrlrequest* req, void* reqdata,
176 unsigned char* dest);
177
178static struct
179{
180 completion_handler_t completion_handler[2];
181 fast_completion_handler_t fast_completion_handler[2];
182 control_handler_t control_handler[2];
183 struct usb_transfer_completion_event_data completion_event[2];
184} ep_data[USB_NUM_ENDPOINTS];
185
186static struct usb_class_driver drivers[USB_NUM_DRIVERS] =
187{
188#ifdef USB_ENABLE_STORAGE
189 [USB_DRIVER_MASS_STORAGE] = {
190 .enabled = false,
191 .needs_exclusive_storage = true,
192 .first_interface = 0,
193 .last_interface = 0,
194 .request_endpoints = usb_storage_request_endpoints,
195 .set_first_interface = usb_storage_set_first_interface,
196 .get_config_descriptor = usb_storage_get_config_descriptor,
197 .init_connection = usb_storage_init_connection,
198 .init = usb_storage_init,
199 .disconnect = usb_storage_disconnect,
200 .transfer_complete = usb_storage_transfer_complete,
201 .control_request = usb_storage_control_request,
202#ifdef HAVE_HOTSWAP
203 .notify_hotswap = usb_storage_notify_hotswap,
204#endif
205 },
206#endif
207#ifdef USB_ENABLE_SERIAL
208 [USB_DRIVER_SERIAL] = {
209 .enabled = false,
210 .needs_exclusive_storage = false,
211 .first_interface = 0,
212 .last_interface = 0,
213 .request_endpoints = usb_serial_request_endpoints,
214 .set_first_interface = usb_serial_set_first_interface,
215 .get_config_descriptor = usb_serial_get_config_descriptor,
216 .init_connection = usb_serial_init_connection,
217 .init = usb_serial_init,
218 .disconnect = usb_serial_disconnect,
219 .transfer_complete = usb_serial_transfer_complete,
220 .control_request = usb_serial_control_request,
221#ifdef HAVE_HOTSWAP
222 .notify_hotswap = NULL,
223#endif
224 },
225#endif
226#ifdef USB_ENABLE_CHARGING_ONLY
227 [USB_DRIVER_CHARGING_ONLY] = {
228 .enabled = false,
229 .needs_exclusive_storage = false,
230 .first_interface = 0,
231 .last_interface = 0,
232 .request_endpoints = usb_charging_only_request_endpoints,
233 .set_first_interface = usb_charging_only_set_first_interface,
234 .get_config_descriptor = usb_charging_only_get_config_descriptor,
235 .init_connection = NULL,
236 .init = NULL,
237 .disconnect = NULL,
238 .transfer_complete = NULL,
239 .control_request = NULL,
240#ifdef HAVE_HOTSWAP
241 .notify_hotswap = NULL,
242#endif
243 },
244#endif
245#ifdef USB_ENABLE_HID
246 [USB_DRIVER_HID] = {
247 .enabled = false,
248 .needs_exclusive_storage = false,
249 .first_interface = 0,
250 .last_interface = 0,
251 .request_endpoints = usb_hid_request_endpoints,
252 .set_first_interface = usb_hid_set_first_interface,
253 .get_config_descriptor = usb_hid_get_config_descriptor,
254 .init_connection = usb_hid_init_connection,
255 .init = usb_hid_init,
256 .disconnect = usb_hid_disconnect,
257 .transfer_complete = usb_hid_transfer_complete,
258 .control_request = usb_hid_control_request,
259#ifdef HAVE_HOTSWAP
260 .notify_hotswap = NULL,
261#endif
262 },
263#endif
264#ifdef USB_ENABLE_AUDIO
265 [USB_DRIVER_AUDIO] = {
266 .enabled = false,
267 .needs_exclusive_storage = false,
268 .first_interface = 0,
269 .last_interface = 0,
270 .request_endpoints = usb_audio_request_endpoints,
271 .set_first_interface = usb_audio_set_first_interface,
272 .get_config_descriptor = usb_audio_get_config_descriptor,
273 .init_connection = usb_audio_init_connection,
274 .init = usb_audio_init,
275 .disconnect = usb_audio_disconnect,
276 .transfer_complete = usb_audio_transfer_complete,
277 .fast_transfer_complete = usb_audio_fast_transfer_complete,
278 .control_request = usb_audio_control_request,
279#ifdef HAVE_HOTSWAP
280 .notify_hotswap = NULL,
281#endif
282 .set_interface = usb_audio_set_interface,
283 .get_interface = usb_audio_get_interface,
284 },
285#endif
286};
287
288#ifdef USB_LEGACY_CONTROL_API
289static struct usb_ctrlrequest buffered_request;
290static struct usb_ctrlrequest* volatile active_request = NULL;
291static volatile unsigned int num_active_requests = 0;
292static void* volatile control_write_data = NULL;
293static volatile bool control_write_data_done = false;
294#endif
295
296static void usb_core_control_request_handler(struct usb_ctrlrequest* req, void* reqdata);
297
298static unsigned char response_data[256] USB_DEVBSS_ATTR;
299
300/** NOTE Serial Number
301 * The serial number string is split into two parts:
302 * - the first character indicates the set of interfaces enabled
303 * - the other characters form a (hopefully) unique device-specific number
304 * The implementation of set_serial_descriptor should left the first character
305 * of usb_string_iSerial unused, ie never write to
306 * usb_string_iSerial.wString[0] but should take it into account when
307 * computing the length of the descriptor
308 */
309
310static const short hex[16] = {'0', '1', '2', '3', '4', '5', '6', '7',
311 '8', '9', 'A', 'B', 'C', 'D', 'E', 'F'};
312#if defined(IPOD_ARCH) && defined(CPU_PP)
313static void set_serial_descriptor(void)
314{
315#ifdef IPOD_VIDEO
316 uint32_t* serial = (uint32_t*)0x20004034;
317#else
318 uint32_t* serial = (uint32_t*)0x20002034;
319#endif
320
321 /* We need to convert from a little-endian 64-bit int
322 into a utf-16 string of hex characters */
323 short* p = &usb_string_iSerial.wString[24];
324 uint32_t x;
325 int i, j;
326
327 for(i = 0; i < 2; i++) {
328 x = serial[i];
329 for(j = 0; j < 8; j++) {
330 *p-- = hex[x & 0xf];
331 x >>= 4;
332 }
333 }
334 usb_string_iSerial.bLength = 52;
335}
336#elif defined(HAVE_AS3514)
337static void set_serial_descriptor(void)
338{
339 unsigned char serial[AS3514_UID_LEN];
340 /* Align 32 digits right in the 40-digit serial number */
341 short* p = &usb_string_iSerial.wString[1];
342 int i;
343
344 ascodec_readbytes(AS3514_UID_0, AS3514_UID_LEN, serial);
345 for(i = 0; i < AS3514_UID_LEN; i++) {
346 *p++ = hex[(serial[i] >> 4) & 0xF];
347 *p++ = hex[(serial[i] >> 0) & 0xF];
348 }
349 usb_string_iSerial.bLength = 36 + (2 * AS3514_UID_LEN);
350}
351#elif (CONFIG_CPU == IMX233) && IMX233_SUBTARGET >= 3700
352// FIXME where is the STMP3600 serial number stored ?
353static void set_serial_descriptor(void)
354{
355 short* p = &usb_string_iSerial.wString[1];
356 for(int i = 0; i < IMX233_NUM_OCOTP_OPS; i++) {
357 uint32_t ops = imx233_ocotp_read(&HW_OCOTP_OPSn(i));
358 for(int j = 0; j < 8; j++) {
359 *p++ = hex[(ops >> 28) & 0xF];
360 ops <<= 4;
361 }
362 }
363 usb_string_iSerial.bLength = 2 + 2 * (1 + IMX233_NUM_OCOTP_OPS * 8);
364}
365#elif defined(SANSA_CONNECT)
366static void set_serial_descriptor(void)
367{
368 char deviceid[32];
369 short* p = &usb_string_iSerial.wString[1];
370 int i;
371
372 if(!cryptomem_read_deviceid(deviceid)) {
373 for(i = 0; i < 32; i++) {
374 *p++ = deviceid[i];
375 }
376 usb_string_iSerial.bLength = 2 + 2 * (1 + 32);
377 } else {
378 device_descriptor.iSerialNumber = 0;
379 }
380}
381#elif (CONFIG_STORAGE & STORAGE_ATA)
382/* If we don't know the device serial number, use the one
383 * from the disk */
384static void set_serial_descriptor(void)
385{
386 short* p = &usb_string_iSerial.wString[1];
387 unsigned short* identify = ata_get_identify();
388 char sn[20];
389 char length = 20;
390 int i;
391
392 for (i = 0; i < length / 2; i++) {
393 ((unsigned short*)sn)[i] = htobe16(identify[i + 10]);
394 }
395
396 char is_printable = 1;
397 for (i = 0; i < length; i++) {
398 if (sn[i] < 32 || sn[i] > 126) {
399 is_printable = 0;
400 break;
401 }
402 }
403
404 if (is_printable) {
405 /* trim ALL spaces */
406 int totallen = length;
407 for (i = 0; i < length; i++) {
408 if (sn[i] == ' ') {
409 totallen--;
410 continue;
411 }
412 *p++ = sn[i];
413 }
414
415 usb_string_iSerial.bLength = 2 + 2 * (1 + totallen);
416 }
417 else {
418 for (i = 0; i < length; i++) {
419 char x = sn[i];
420 *p++ = hex[(x >> 4) & 0xF];
421 *p++ = hex[x & 0xF];
422 }
423
424 usb_string_iSerial.bLength = 2 + 2 * (1 + length * 2);
425 }
426}
427#elif (CONFIG_STORAGE & STORAGE_RAMDISK)
428/* This "serial number" isn't unique, but it should never actually
429 appear in non-testing use */
430static void set_serial_descriptor(void)
431{
432 short* p = &usb_string_iSerial.wString[1];
433 int i;
434 for(i = 0; i < 16; i++) {
435 *p++ = hex[(2 * i) & 0xF];
436 *p++ = hex[(2 * i + 1) & 0xF];
437 }
438 usb_string_iSerial.bLength = 68;
439}
440#else
441static void set_serial_descriptor(void)
442{
443 device_descriptor.iSerialNumber = 0;
444}
445#endif
446
447void usb_core_init(void)
448{
449 int i;
450 if (initialized)
451 return;
452
453 usb_drv_init();
454
455 /* class driver init functions should be safe to call even if the driver
456 * won't be used. This simplifies other logic (i.e. we don't need to know
457 * yet which drivers will be enabled */
458 for(i = 0; i < USB_NUM_DRIVERS; i++)
459 if(drivers[i].init != NULL)
460 drivers[i].init();
461
462 initialized = true;
463 usb_state = DEFAULT;
464#ifdef HAVE_USB_CHARGING_ENABLE
465 usb_no_host = false;
466 timeout_register(&usb_no_host_timeout, usb_no_host_callback, HZ*10, 0);
467#endif
468 logf("usb_core_init() finished");
469}
470
471void usb_core_exit(void)
472{
473 int i;
474 if(drivers_connected)
475 {
476 for(i = 0; i < USB_NUM_DRIVERS; i++)
477 if(drivers[i].enabled && drivers[i].disconnect != NULL)
478 {
479 drivers[i].disconnect();
480 drivers[i].enabled = false;
481 }
482 drivers_connected = false;
483 }
484
485 if(initialized) {
486 usb_drv_exit();
487 initialized = false;
488 }
489 usb_state = DEFAULT;
490#ifdef HAVE_USB_CHARGING_ENABLE
491 usb_no_host = false;
492 usb_charging_maxcurrent_change(usb_charging_maxcurrent());
493#endif
494 logf("usb_core_exit() finished");
495}
496
497void usb_core_handle_transfer_completion(
498 struct usb_transfer_completion_event_data* event)
499{
500 completion_handler_t handler;
501 int ep = event->endpoint;
502
503 switch(ep) {
504 case EP_CONTROL:
505 logf("ctrl handled %ld req=0x%x",
506 current_tick,
507 ((struct usb_ctrlrequest*)event->data[0])->bRequest);
508
509 usb_core_control_request_handler(
510 (struct usb_ctrlrequest*)event->data[0], event->data[1]);
511 break;
512 default:
513 handler = ep_data[ep].completion_handler[EP_DIR(event->dir)];
514 if(handler != NULL)
515 handler(ep, event->dir, event->status, event->length);
516 break;
517 }
518}
519
520void usb_core_enable_driver(int driver, bool enabled)
521{
522 drivers[driver].enabled = enabled;
523}
524
525bool usb_core_driver_enabled(int driver)
526{
527 return drivers[driver].enabled;
528}
529
530bool usb_core_any_exclusive_storage(void)
531{
532 int i;
533 for(i = 0; i < USB_NUM_DRIVERS; i++)
534 if(drivers[i].enabled && drivers[i].needs_exclusive_storage)
535 return true;
536
537 return false;
538}
539
540#ifdef HAVE_HOTSWAP
541void usb_core_hotswap_event(int volume, bool inserted)
542{
543 int i;
544 for(i = 0; i < USB_NUM_DRIVERS; i++)
545 if(drivers[i].enabled && drivers[i].notify_hotswap != NULL)
546 drivers[i].notify_hotswap(volume, inserted);
547}
548#endif
549
550static void usb_core_set_serial_function_id(void)
551{
552 int i, id = 0;
553
554 for(i = 0; i < USB_NUM_DRIVERS; i++)
555 if(drivers[i].enabled)
556 id |= 1 << i;
557
558 usb_string_iSerial.wString[0] = hex[id];
559}
560
561int usb_core_request_endpoint(int type, int dir, struct usb_class_driver* drv)
562{
563 int ret, ep;
564
565 ret = usb_drv_request_endpoint(type, dir);
566
567 if(ret == -1)
568 return -1;
569
570 dir = EP_DIR(ret);
571 ep = EP_NUM(ret);
572
573 ep_data[ep].completion_handler[dir] = drv->transfer_complete;
574 ep_data[ep].fast_completion_handler[dir] = drv->fast_transfer_complete;
575 ep_data[ep].control_handler[dir] = drv->control_request;
576
577 return ret;
578}
579
580void usb_core_release_endpoint(int ep)
581{
582 int dir;
583
584 usb_drv_release_endpoint(ep);
585
586 dir = EP_DIR(ep);
587 ep = EP_NUM(ep);
588
589 ep_data[ep].completion_handler[dir] = NULL;
590 ep_data[ep].control_handler[dir] = NULL;
591}
592
593static void allocate_interfaces_and_endpoints(void)
594{
595 int i;
596 int interface = 0;
597
598 memset(ep_data, 0, sizeof(ep_data));
599
600 for(i = 0; i < USB_NUM_ENDPOINTS; i++) {
601 usb_drv_release_endpoint(i | USB_DIR_OUT);
602 usb_drv_release_endpoint(i | USB_DIR_IN);
603 }
604
605 for(i = 0; i < USB_NUM_DRIVERS; i++) {
606 if(drivers[i].enabled) {
607 drivers[i].first_interface = interface;
608
609 if(drivers[i].request_endpoints(&drivers[i])) {
610 drivers[i].enabled = false;
611 continue;
612 }
613
614 interface = drivers[i].set_first_interface(interface);
615 drivers[i].last_interface = interface;
616 }
617 }
618 usb_core_num_interfaces = interface;
619}
620
621
622static void control_request_handler_drivers(struct usb_ctrlrequest* req, void* reqdata)
623{
624 int i, interface = req->wIndex & 0xff;
625 bool handled = false;
626
627 for(i = 0; i < USB_NUM_DRIVERS; i++) {
628 if(drivers[i].enabled &&
629 drivers[i].control_request &&
630 drivers[i].first_interface <= interface &&
631 drivers[i].last_interface > interface) {
632 /* Check for SET_INTERFACE and GET_INTERFACE */
633 if((req->bRequestType & USB_RECIP_MASK) == USB_RECIP_INTERFACE &&
634 (req->bRequestType & USB_TYPE_MASK) == USB_TYPE_STANDARD) {
635
636 if(req->bRequest == USB_REQ_SET_INTERFACE) {
637 logf("usb_core: SET INTERFACE 0x%x 0x%x", req->wValue, req->wIndex);
638 if(drivers[i].set_interface &&
639 drivers[i].set_interface(req->wIndex, req->wValue) >= 0) {
640
641 usb_drv_control_response(USB_CONTROL_ACK, NULL, 0);
642 handled = true;
643 }
644 break;
645 }
646 else if(req->bRequest == USB_REQ_GET_INTERFACE) {
647 int alt = -1;
648 logf("usb_core: GET INTERFACE 0x%x", req->wIndex);
649
650 if(drivers[i].get_interface)
651 alt = drivers[i].get_interface(req->wIndex);
652
653 if(alt >= 0 && alt < 255) {
654 response_data[0] = alt;
655 usb_drv_control_response(USB_CONTROL_ACK, response_data, 1);
656 handled = true;
657 }
658 break;
659 }
660 /* fallback */
661 }
662
663 handled = drivers[i].control_request(req, reqdata, response_data);
664 break; /* no other driver can handle it because it's interface specific */
665 }
666 }
667 if(!handled) {
668 /* nope. flag error */
669 logf("bad req 0x%x:0x%x:0x%x:0x%x:0x%x", req->bRequestType,req->bRequest,
670 req->wValue, req->wIndex, req->wLength);
671 usb_drv_control_response(USB_CONTROL_STALL, NULL, 0);
672 }
673}
674
675static void request_handler_device_get_descriptor(struct usb_ctrlrequest* req, void* reqdata)
676{
677 int size;
678 const void* ptr = NULL;
679 int length = req->wLength;
680 int index = req->wValue & 0xff;
681
682 switch(req->wValue >> 8) { /* type */
683 case USB_DT_DEVICE:
684 ptr = &device_descriptor;
685 size = sizeof(struct usb_device_descriptor);
686 break;
687
688 case USB_DT_OTHER_SPEED_CONFIG:
689 case USB_DT_CONFIG: {
690 int i, max_packet_size;
691
692 if(req->wValue>>8==USB_DT_CONFIG) {
693 max_packet_size = (usb_drv_port_speed() ? 512 : 64);
694 config_descriptor.bDescriptorType = USB_DT_CONFIG;
695 }
696 else {
697 max_packet_size=(usb_drv_port_speed() ? 64 : 512);
698 config_descriptor.bDescriptorType =
699 USB_DT_OTHER_SPEED_CONFIG;
700 }
701#ifdef HAVE_USB_CHARGING_ENABLE
702 if (usb_charging_mode == USB_CHARGING_DISABLE) {
703 config_descriptor.bMaxPower = (100+1)/2;
704 usb_charging_current_requested = 100;
705 }
706 else {
707 config_descriptor.bMaxPower = (500+1)/2;
708 usb_charging_current_requested = 500;
709 }
710#endif
711 size = sizeof(struct usb_config_descriptor);
712
713 for(i = 0; i < USB_NUM_DRIVERS; i++)
714 if(drivers[i].enabled && drivers[i].get_config_descriptor)
715 size += drivers[i].get_config_descriptor(
716 &response_data[size], max_packet_size);
717
718 config_descriptor.bNumInterfaces = usb_core_num_interfaces;
719 config_descriptor.wTotalLength = (uint16_t)size;
720 memcpy(&response_data[0], &config_descriptor,
721 sizeof(struct usb_config_descriptor));
722
723 ptr = response_data;
724 break;
725 }
726
727 case USB_DT_STRING:
728 logf("STRING %d", index);
729 if((unsigned)index < USB_STRING_INDEX_MAX) {
730 size = usb_strings[index]->bLength;
731 ptr = usb_strings[index];
732 }
733 else if(index == 0xee) {
734 /* We don't have a real OS descriptor, and we don't handle
735 * STALL correctly on some devices, so we return any valid
736 * string (we arbitrarily pick the manufacturer name)
737 */
738 size = usb_string_iManufacturer.bLength;
739 ptr = &usb_string_iManufacturer;
740 }
741 else {
742 logf("bad string id %d", index);
743 ptr = NULL;
744 }
745 break;
746
747 case USB_DT_DEVICE_QUALIFIER:
748 ptr = &qualifier_descriptor;
749 size = sizeof(struct usb_qualifier_descriptor);
750 break;
751
752 default:
753 logf("ctrl desc.");
754 control_request_handler_drivers(req, reqdata);
755 return;
756 }
757
758 if(ptr) {
759 logf("data %d (%d)", size, length);
760 length = MIN(size, length);
761
762 if (ptr != response_data)
763 memcpy(response_data, ptr, length);
764
765 usb_drv_control_response(USB_CONTROL_ACK, response_data, length);
766 } else {
767 usb_drv_control_response(USB_CONTROL_STALL, NULL, 0);
768 }
769}
770
771static void usb_core_do_set_addr(uint8_t address)
772{
773 logf("usb_core: SET_ADR %d", address);
774 usb_address = address;
775 usb_state = ADDRESS;
776}
777
778static void usb_core_do_set_config(uint8_t config)
779{
780 logf("usb_core: SET_CONFIG %d",config);
781 if(config) {
782 usb_state = CONFIGURED;
783
784 if(drivers_connected)
785 for(int i = 0; i < USB_NUM_DRIVERS; i++)
786 if(drivers[i].enabled && drivers[i].disconnect != NULL)
787 drivers[i].disconnect();
788
789 for(int i = 0; i < USB_NUM_DRIVERS; i++)
790 if(drivers[i].enabled && drivers[i].init_connection)
791 drivers[i].init_connection();
792 drivers_connected = true;
793 }
794 else
795 usb_state = ADDRESS;
796 #ifdef HAVE_USB_CHARGING_ENABLE
797 usb_charging_maxcurrent_change(usb_charging_maxcurrent());
798 #endif
799}
800
801static void usb_core_do_clear_feature(int recip, int recip_nr, int feature)
802{
803 logf("usb_core: CLEAR FEATURE (%d,%d,%d)", recip, recip_nr, feature);
804 if(recip == USB_RECIP_ENDPOINT)
805 {
806 if(feature == USB_ENDPOINT_HALT)
807 usb_drv_stall(EP_NUM(recip_nr), false, EP_DIR(recip_nr));
808 }
809}
810
811static void request_handler_device(struct usb_ctrlrequest* req, void* reqdata)
812{
813 unsigned address;
814
815 switch(req->bRequest) {
816 case USB_REQ_GET_CONFIGURATION:
817 logf("usb_core: GET_CONFIG");
818 response_data[0] = (usb_state == ADDRESS ? 0 : 1);
819 usb_drv_control_response(USB_CONTROL_ACK, response_data, 1);
820 break;
821 case USB_REQ_SET_CONFIGURATION:
822 usb_drv_cancel_all_transfers();
823 usb_core_do_set_config(req->wValue);
824 usb_drv_control_response(USB_CONTROL_ACK, NULL, 0);
825 break;
826 case USB_REQ_SET_ADDRESS:
827 /* NOTE: We really have no business handling this and drivers
828 * should just handle it themselves. We don't care beyond
829 * knowing if we've been assigned an address yet, or not. */
830 address = req->wValue;
831 usb_drv_control_response(USB_CONTROL_ACK, NULL, 0);
832 usb_drv_cancel_all_transfers();
833 usb_drv_set_address(address);
834 usb_core_do_set_addr(address);
835 break;
836 case USB_REQ_GET_DESCRIPTOR:
837 logf("usb_core: GET_DESC %d", req->wValue >> 8);
838 request_handler_device_get_descriptor(req, reqdata);
839 break;
840 case USB_REQ_SET_FEATURE:
841 if(req->wValue==USB_DEVICE_TEST_MODE) {
842 int mode = req->wIndex >> 8;
843 usb_drv_control_response(USB_CONTROL_ACK, NULL, 0);
844 usb_drv_set_test_mode(mode);
845 } else {
846 usb_drv_control_response(USB_CONTROL_STALL, NULL, 0);
847 }
848 break;
849 case USB_REQ_GET_STATUS:
850 response_data[0] = 0;
851 response_data[1] = 0;
852 usb_drv_control_response(USB_CONTROL_ACK, response_data, 2);
853 break;
854 default:
855 logf("bad req:desc %d:%d", req->bRequest, req->wValue);
856 usb_drv_control_response(USB_CONTROL_STALL, NULL, 0);
857 break;
858 }
859}
860
861static void request_handler_interface_standard(struct usb_ctrlrequest* req, void* reqdata)
862{
863 switch (req->bRequest)
864 {
865 case USB_REQ_SET_INTERFACE:
866 logf("usb_core: SET_INTERFACE");
867 case USB_REQ_GET_INTERFACE:
868 control_request_handler_drivers(req, reqdata);
869 break;
870 break;
871 case USB_REQ_GET_STATUS:
872 response_data[0] = 0;
873 response_data[1] = 0;
874 usb_drv_control_response(USB_CONTROL_ACK, response_data, 2);
875 break;
876 case USB_REQ_CLEAR_FEATURE:
877 case USB_REQ_SET_FEATURE:
878 /* TODO: These used to be ignored (erroneously).
879 * Should they be passed to the drivers instead? */
880 usb_drv_control_response(USB_CONTROL_STALL, NULL, 0);
881 break;
882 default:
883 control_request_handler_drivers(req, reqdata);
884 break;
885 }
886}
887
888static void request_handler_interface(struct usb_ctrlrequest* req, void* reqdata)
889{
890 switch(req->bRequestType & USB_TYPE_MASK) {
891 case USB_TYPE_STANDARD:
892 request_handler_interface_standard(req, reqdata);
893 break;
894 case USB_TYPE_CLASS:
895 control_request_handler_drivers(req, reqdata);
896 break;
897 case USB_TYPE_VENDOR:
898 default:
899 logf("bad req:desc %d", req->bRequest);
900 usb_drv_control_response(USB_CONTROL_STALL, NULL, 0);
901 break;
902 }
903}
904
905static void request_handler_endpoint_drivers(struct usb_ctrlrequest* req, void* reqdata)
906{
907 bool handled = false;
908 control_handler_t control_handler = NULL;
909
910 if(EP_NUM(req->wIndex) < USB_NUM_ENDPOINTS)
911 control_handler =
912 ep_data[EP_NUM(req->wIndex)].control_handler[EP_DIR(req->wIndex)];
913
914 if(control_handler)
915 handled = control_handler(req, reqdata, response_data);
916
917 if(!handled) {
918 /* nope. flag error */
919 logf("bad req 0x%x:0x%x:0x%x:0x%x:0x%x", req->bRequestType,req->bRequest,
920 req->wValue, req->wIndex, req->wLength);
921 usb_drv_control_response(USB_CONTROL_STALL, NULL, 0);
922 }
923}
924
925static void request_handler_endpoint_standard(struct usb_ctrlrequest* req, void* reqdata)
926{
927 switch (req->bRequest) {
928 case USB_REQ_CLEAR_FEATURE:
929 usb_core_do_clear_feature(USB_RECIP_ENDPOINT,
930 req->wIndex,
931 req->wValue);
932 usb_drv_control_response(USB_CONTROL_ACK, NULL, 0);
933 break;
934 case USB_REQ_SET_FEATURE:
935 logf("usb_core: SET FEATURE (%d)", req->wValue);
936 if(req->wValue == USB_ENDPOINT_HALT)
937 usb_drv_stall(EP_NUM(req->wIndex), true, EP_DIR(req->wIndex));
938
939 usb_drv_control_response(USB_CONTROL_ACK, NULL, 0);
940 break;
941 case USB_REQ_GET_STATUS:
942 response_data[0] = 0;
943 response_data[1] = 0;
944 logf("usb_core: GET_STATUS");
945 if(req->wIndex > 0)
946 response_data[0] = usb_drv_stalled(EP_NUM(req->wIndex),
947 EP_DIR(req->wIndex));
948
949 usb_drv_control_response(USB_CONTROL_ACK, response_data, 2);
950 break;
951 default:
952 request_handler_endpoint_drivers(req, reqdata);
953 break;
954 }
955}
956
957static void request_handler_endpoint(struct usb_ctrlrequest* req, void* reqdata)
958{
959 switch(req->bRequestType & USB_TYPE_MASK) {
960 case USB_TYPE_STANDARD:
961 request_handler_endpoint_standard(req, reqdata);
962 break;
963 case USB_TYPE_CLASS:
964 request_handler_endpoint_drivers(req, reqdata);
965 break;
966 case USB_TYPE_VENDOR:
967 default:
968 logf("bad req:desc %d", req->bRequest);
969 usb_drv_control_response(USB_CONTROL_STALL, NULL, 0);
970 break;
971 }
972}
973
974/* Handling USB requests starts here */
975static void usb_core_control_request_handler(struct usb_ctrlrequest* req, void* reqdata)
976{
977#ifdef HAVE_USB_CHARGING_ENABLE
978 timeout_cancel(&usb_no_host_timeout);
979 if(usb_no_host) {
980 usb_no_host = false;
981 usb_charging_maxcurrent_change(usb_charging_maxcurrent());
982 }
983#endif
984 if(usb_state == DEFAULT) {
985 set_serial_descriptor();
986 usb_core_set_serial_function_id();
987
988 allocate_interfaces_and_endpoints();
989 }
990
991 switch(req->bRequestType & USB_RECIP_MASK) {
992 case USB_RECIP_DEVICE:
993 request_handler_device(req, reqdata);
994 break;
995 case USB_RECIP_INTERFACE:
996 request_handler_interface(req, reqdata);
997 break;
998 case USB_RECIP_ENDPOINT:
999 request_handler_endpoint(req, reqdata);
1000 break;
1001 default:
1002 logf("unsupported recipient");
1003 usb_drv_control_response(USB_CONTROL_STALL, NULL, 0);
1004 break;
1005 }
1006}
1007
1008/* called by usb_drv_int() */
1009void usb_core_bus_reset(void)
1010{
1011 logf("usb_core: bus reset");
1012 usb_address = 0;
1013 usb_state = DEFAULT;
1014#ifdef HAVE_USB_CHARGING_ENABLE
1015#ifdef HAVE_USB_CHARGING_IN_THREAD
1016 /* On some targets usb_charging_maxcurrent_change() cannot be called
1017 * from an interrupt handler; get the USB thread to do it instead. */
1018 usb_charger_update();
1019#else
1020 usb_charging_maxcurrent_change(usb_charging_maxcurrent());
1021#endif
1022#endif
1023}
1024
1025/* called by usb_drv_transfer_completed() */
1026void usb_core_transfer_complete(int endpoint, int dir, int status, int length)
1027{
1028 struct usb_transfer_completion_event_data* completion_event =
1029 &ep_data[endpoint].completion_event[EP_DIR(dir)];
1030 /* Fast notification */
1031 fast_completion_handler_t handler = ep_data[endpoint].fast_completion_handler[EP_DIR(dir)];
1032 if(handler != NULL && handler(endpoint, dir, status, length))
1033 return; /* do not dispatch to the queue if handled */
1034
1035 void* data0 = NULL;
1036 void* data1 = NULL;
1037
1038#ifdef USB_LEGACY_CONTROL_API
1039 if(endpoint == EP_CONTROL) {
1040 bool cwdd = control_write_data_done;
1041 struct usb_ctrlrequest* req = active_request;
1042
1043 if(dir == USB_DIR_OUT && req && cwdd) {
1044 data0 = req;
1045 data1 = control_write_data;
1046 } else {
1047 return;
1048 }
1049 }
1050#endif
1051
1052 completion_event->endpoint = endpoint;
1053 completion_event->dir = dir;
1054 completion_event->data[0] = data0;
1055 completion_event->data[1] = data1;
1056 completion_event->status = status;
1057 completion_event->length = length;
1058
1059 usb_signal_transfer_completion(completion_event);
1060}
1061
1062void usb_core_handle_notify(long id, intptr_t data)
1063{
1064 switch(id)
1065 {
1066 case USB_NOTIFY_SET_ADDR:
1067 usb_core_do_set_addr(data);
1068 break;
1069 case USB_NOTIFY_SET_CONFIG:
1070 usb_core_do_set_config(data);
1071 break;
1072 default:
1073 break;
1074 }
1075}
1076
1077void usb_core_control_request(struct usb_ctrlrequest* req, void* reqdata)
1078{
1079 struct usb_transfer_completion_event_data* completion_event =
1080 &ep_data[EP_CONTROL].completion_event[EP_DIR(USB_DIR_IN)];
1081
1082 completion_event->endpoint = EP_CONTROL;
1083 completion_event->dir = 0;
1084 completion_event->data[0] = (void*)req;
1085 completion_event->data[1] = reqdata;
1086 completion_event->status = 0;
1087 completion_event->length = 0;
1088 logf("ctrl received %ld, req=0x%x", current_tick, req->bRequest);
1089 usb_signal_transfer_completion(completion_event);
1090}
1091
1092void usb_core_control_complete(int status)
1093{
1094 /* We currently don't use this, it's here to make the API look good ;)
1095 * It makes sense to #define it away on normal builds.
1096 */
1097 (void)status;
1098 logf("ctrl complete %ld, %d", current_tick, status);
1099}
1100
1101#ifdef USB_LEGACY_CONTROL_API
1102/* Only needed if the driver does not support the new API yet */
1103void usb_core_legacy_control_request(struct usb_ctrlrequest* req)
1104{
1105 /* Only submit non-overlapping requests */
1106 if (num_active_requests++ == 0)
1107 {
1108 buffered_request = *req;
1109 active_request = &buffered_request;
1110 control_write_data = NULL;
1111 control_write_data_done = false;
1112
1113 usb_core_control_request(req, NULL);
1114 }
1115}
1116
1117void usb_drv_control_response(enum usb_control_response resp,
1118 void* data, int length)
1119{
1120 struct usb_ctrlrequest* req = active_request;
1121 unsigned int num_active = num_active_requests--;
1122
1123 /*
1124 * There should have been a prior request submission, at least.
1125 * FIXME: It seems the iPod video can get here and ignoring it
1126 * allows the connection to succeed??
1127 */
1128 if (num_active == 0)
1129 {
1130 //panicf("null ctrl req");
1131 return;
1132 }
1133
1134 /*
1135 * This can happen because an active request was already pending when
1136 * the driver submitted a new one in usb_core_legacy_control_request().
1137 * This could mean two things: (a) a driver bug; or (b) the host sent
1138 * another request because we were too slow in handling an earlier one.
1139 *
1140 * The USB spec requires we respond to the latest request and drop any
1141 * earlier ones, but that's not easy to do with the current design of
1142 * the USB stack. Thus, the host will be expecting a response for the
1143 * latest request, but this response is for the _earliest_ request.
1144 *
1145 * Play it safe and return a STALL. At this point we've recovered from
1146 * the error on our end and will be ready to handle the next request.
1147 */
1148 if (num_active > 1)
1149 {
1150 active_request = NULL;
1151 num_active_requests = 0;
1152 usb_drv_stall(EP_CONTROL, true, true);
1153 return;
1154 }
1155
1156 if(req->wLength == 0)
1157 {
1158 active_request = NULL;
1159
1160 /* No-data request */
1161 if(resp == USB_CONTROL_ACK)
1162 usb_drv_send(EP_CONTROL, data, length);
1163 else if(resp == USB_CONTROL_STALL)
1164 usb_drv_stall(EP_CONTROL, true, true);
1165 else
1166 panicf("RECEIVE on non-data req");
1167 }
1168 else if(req->bRequestType & USB_DIR_IN)
1169 {
1170 /* Control read request */
1171 if(resp == USB_CONTROL_ACK)
1172 {
1173 active_request = NULL;
1174 usb_drv_recv_nonblocking(EP_CONTROL, NULL, 0);
1175 usb_drv_send(EP_CONTROL, data, length);
1176 }
1177 else if(resp == USB_CONTROL_STALL)
1178 {
1179 active_request = NULL;
1180 usb_drv_stall(EP_CONTROL, true, true);
1181 }
1182 else
1183 {
1184 panicf("RECEIVE on ctrl read req");
1185 }
1186 }
1187 else if(!control_write_data_done)
1188 {
1189 /* Control write request, data phase */
1190 if(resp == USB_CONTROL_RECEIVE)
1191 {
1192 control_write_data = data;
1193 control_write_data_done = true;
1194 usb_drv_recv_nonblocking(EP_CONTROL, data, length);
1195 }
1196 else if(resp == USB_CONTROL_STALL)
1197 {
1198 /* We should stall the OUT endpoint here, but the old code did
1199 * not do so and some drivers may not handle it correctly. */
1200 active_request = NULL;
1201 usb_drv_stall(EP_CONTROL, true, true);
1202 }
1203 else
1204 {
1205 panicf("ACK on ctrl write data");
1206 }
1207 }
1208 else
1209 {
1210 active_request = NULL;
1211 control_write_data = NULL;
1212 control_write_data_done = false;
1213
1214 /* Control write request, status phase */
1215 if(resp == USB_CONTROL_ACK)
1216 usb_drv_send(EP_CONTROL, NULL, 0);
1217 else if(resp == USB_CONTROL_STALL)
1218 usb_drv_stall(EP_CONTROL, true, true);
1219 else
1220 panicf("RECEIVE on ctrl write status");
1221 }
1222}
1223#endif
1224
1225void usb_core_notify_set_address(uint8_t addr)
1226{
1227 logf("notify set addr received %ld", current_tick);
1228 usb_signal_notify(USB_NOTIFY_SET_ADDR, addr);
1229}
1230
1231void usb_core_notify_set_config(uint8_t config)
1232{
1233 logf("notify set config received %ld", current_tick);
1234 usb_signal_notify(USB_NOTIFY_SET_CONFIG, config);
1235}
1236
1237#ifdef HAVE_USB_CHARGING_ENABLE
1238void usb_charging_enable(int state)
1239{
1240 usb_charging_mode = state;
1241 usb_charging_maxcurrent_change(usb_charging_maxcurrent());
1242}
1243
1244int usb_charging_maxcurrent()
1245{
1246 if (!initialized || usb_charging_mode == USB_CHARGING_DISABLE)
1247 return 100;
1248 if (usb_state == CONFIGURED)
1249 return usb_charging_current_requested;
1250 if (usb_charging_mode == USB_CHARGING_FORCE && usb_no_host)
1251 return 500;
1252 return 100;
1253}
1254#endif