/* ** $Id$ ** Type definitions for Lua objects ** See Copyright Notice in lua.h */ #ifndef lobject_h #define lobject_h #include #include "llimits.h" #include "lua.h" /* tags for values visible from Lua */ #define LAST_TAG LUA_TTHREAD #define NUM_TAGS (LAST_TAG+1) /* ** Extra tags for non-values */ #define LUA_TPROTO (LAST_TAG+1) #define LUA_TUPVAL (LAST_TAG+2) #define LUA_TDEADKEY (LAST_TAG+3) /* ** Union of all collectable objects */ typedef union GCObject GCObject; /* ** Common Header for all collectable objects (in macro form, to be ** included in other objects) */ #define CommonHeader GCObject *next; lu_byte tt; lu_byte marked /* ** Common header in struct form */ typedef struct GCheader { CommonHeader; } GCheader; /* ** Union of all Lua values */ typedef union { GCObject *gc; void *p; lua_Number n; int b; } Value; /* ** Tagged Values */ #define TValuefields Value value; int tt typedef struct lua_TValue { TValuefields; } TValue; /* Macros to test type */ #define ttisnil(o) (ttype(o) == LUA_TNIL) #define ttisnumber(o) (ttype(o) == LUA_TNUMBER) #define ttisstring(o) (ttype(o) == LUA_TSTRING) #define ttistable(o) (ttype(o) == LUA_TTABLE) #define ttisfunction(o) (ttype(o) == LUA_TFUNCTION) #define ttisboolean(o) (ttype(o) == LUA_TBOOLEAN) #define ttisuserdata(o) (ttype(o) == LUA_TUSERDATA) #define ttisthread(o) (ttype(o) == LUA_TTHREAD) #define ttislightuserdata(o) (ttype(o) == LUA_TLIGHTUSERDATA) /* Macros to access values */ #define ttype(o) ((o)->tt) #define gcvalue(o) check_exp(iscollectable(o), (o)->value.gc) #define pvalue(o) check_exp(ttislightuserdata(o), (o)->value.p) #define nvalue(o) check_exp(ttisnumber(o), (o)->value.n) #define rawtsvalue(o) check_exp(ttisstring(o), &(o)->value.gc->ts) #define tsvalue(o) (&rawtsvalue(o)->tsv) #define rawuvalue(o) check_exp(ttisuserdata(o), &(o)->value.gc->u) #define uvalue(o) (&rawuvalue(o)->uv) #define clvalue(o) check_exp(ttisfunction(o), &(o)->value.gc->cl) #define hvalue(o) check_exp(ttistable(o), &(o)->value.gc->h) #define bvalue(o) check_exp(ttisboolean(o), (o)->value.b) #define thvalue(o) check_exp(ttisthread(o), &(o)->value.gc->th) #define l_isfalse(o) (ttisnil(o) || (ttisboolean(o) && bvalue(o) == 0)) /* ** for internal debug only */ #define checkconsistency(obj) \ lua_assert(!iscollectable(obj) || (ttype(obj) == (obj)->value.gc->gch.tt)) #define checkliveness(g,obj) \ lua_assert(!iscollectable(obj) || \ ((ttype(obj) == (obj)->value.gc->gch.tt) && !isdead(g, (obj)->value.gc))) /* Macros to set values */ #define setnilvalue(obj) ((obj)->tt=LUA_TNIL) #define setnvalue(obj,x) \ { TValue *i_o=(obj); i_o->value.n=(x); i_o->tt=LUA_TNUMBER; } #define setpvalue(obj,x) \ { TValue *i_o=(obj); i_o->value.p=(x); i_o->tt=LUA_TLIGHTUSERDATA; } #define setbvalue(obj,x) \ { TValue *i_o=(obj); i_o->value.b=(x); i_o->tt=LUA_TBOOLEAN; } #define setsvalue(L,obj,x) \ { TValue *i_o=(obj); \ i_o->value.gc=cast(GCObject *, (x)); i_o->tt=LUA_TSTRING; \ checkliveness(G(L),i_o); } #define setuvalue(L,obj,x) \ { TValue *i_o=(obj); \ i_o->value.gc=cast(GCObject *, (x)); i_o->tt=LUA_TUSERDATA; \ checkliveness(G(L),i_o); } #define setthvalue(L,obj,x) \ { TValue *i_o=(obj); \ i_o->value.gc=cast(GCObject *, (x)); i_o->tt=LUA_TTHREAD; \ checkliveness(G(L),i_o); } #define setclvalue(L,obj,x) \ { TValue *i_o=(obj); \ i_o->value.gc=cast(GCObject *, (x)); i_o->tt=LUA_TFUNCTION; \ checkliveness(G(L),i_o); } #define sethvalue(L,obj,x) \ { TValue *i_o=(obj); \ i_o->value.gc=cast(GCObject *, (x)); i_o->tt=LUA_TTABLE; \ checkliveness(G(L),i_o); } #define setptvalue(L,obj,x) \ { TValue *i_o=(obj); \ i_o->value.gc=cast(GCObject *, (x)); i_o->tt=LUA_TPROTO; \ checkliveness(G(L),i_o); } #define setobj(L,obj1,obj2) \ { const TValue *o2=(obj2); TValue *o1=(obj1); \ o1->value = o2->value; o1->tt=o2->tt; \ checkliveness(G(L),o1); } /* ** different types of sets, according to destination */ /* from stack to (same) stack */ #define setobjs2s setobj /* to stack (not from same stack) */ #define setobj2s setobj #define setsvalue2s setsvalue #define sethvalue2s sethvalue #define setptvalue2s setptvalue /* from table to same table */ #define setobjt2t setobj /* to table */ #define setobj2t setobj /* to new object */ #define setobj2n setobj #define setsvalue2n setsvalue #define setttype(obj, tt) (ttype(obj) = (tt)) #define iscollectable(o) (ttype(o) >= LUA_TSTRING) typedef TValue *StkId; /* index to stack elements */ /* ** String headers for string table */ typedef union TString { L_Umaxalign dummy; /* ensures maximum alignment for strings */ struct { CommonHeader; lu_byte reserved; unsigned int hash; size_t len; } tsv; } TString; #define getstr(ts) cast(const char *, (ts) + 1) #define svalue(o) getstr(rawtsvalue(o)) typedef union Udata { L_Umaxalign dummy; /* ensures maximum alignment for `local' udata */ struct { CommonHeader; struct Table *metatable; struct Table *env; size_t len; } uv; } Udata; /* ** Function Prototypes */ typedef struct Proto { CommonHeader; TValue *k; /* constants used by the function */ Instruction *code; struct Proto **p; /* functions defined inside the function */ int *lineinfo; /* map from opcodes to source lines */ struct LocVar *locvars; /* information about local variables */ TString **upvalues; /* upvalue names */ TString *source; int sizeupvalues; int sizek; /* size of `k' */ int sizecode; int sizelineinfo; int sizep; /* size of `p' */ int sizelocvars; int linedefined; int lastlinedefined; GCObject *gclist; lu_byte nups; /* number of upvalues */ lu_byte numparams; lu_byte is_vararg; lu_byte maxstacksize; } Proto; /* masks for new-style vararg */ #define VARARG_HASARG 1 #define VARARG_ISVARARG 2 #define VARARG_NEEDSARG 4 typedef struct LocVar { TString *varname; int startpc; /* first point where variable is active */ int endpc; /* first point where variable is dead */ } LocVar; /* ** Upvalues */ typedef struct UpVal { CommonHeader; TValue *v; /* points to stack or to its own value */ union { TValue value; /* the value (when closed) */ struct { /* double linked list (when open) */ struct UpVal *prev; struct UpVal *next; } l; } u; } UpVal; /* ** Closures */ #define ClosureHeader \ CommonHeader; lu_byte isC; lu_byte nupvalues; GCObject *gclist; \ struct Table *env typedef struct CClosure { ClosureHeader; lua_CFunction f; TValue upvalue[1]; } CClosure; typedef struct LClosure { ClosureHeader; struct Proto *p; UpVal *upvals[1]; } LClosure; typedef union Closure { CClosure c; LClosure l; } Closure; #define iscfunction(o) (ttype(o) == LUA_TFUNCTION && clvalue(o)->c.isC) #define isLfunction(o) (ttype(o) == LUA_TFUNCTION && !clvalue(o)->c.isC) /* ** Tables */ typedef union TKey { struct { TValuefields; struct Node *next; /* for chaining */ } nk; TValue tvk; } TKey; typedef struct Node { TValue i_val; TKey i_key; } Node; typedef struct Table { CommonHeader; lu_byte flags; /* 1<

lsizenode)) #define luaO_nilobject (&luaO_nilobject_) LUAI_DATA const TValue luaO_nilobject_; #define ceillog2(x) (luaO_log2((x)-1) + 1) LUAI_FUNC int luaO_log2 (unsigned int x); LUAI_FUNC int luaO_int2fb (unsigned int x); LUAI_FUNC int luaO_fb2int (int x); LUAI_FUNC int luaO_rawequalObj (const TValue *t1, const TValue *t2); LUAI_FUNC int luaO_str2d (const char *s, lua_Number *result); LUAI_FUNC const char *luaO_pushvfstring (lua_State *L, const char *fmt, va_list argp); LUAI_FUNC const char *luaO_pushfstring (lua_State *L, const char *fmt, ...); LUAI_FUNC void luaO_chunkid (char *out, const char *source, size_t len); #endif n167'>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 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811

/***************************************************************************
 *             __________               __   ___.
 *   Open      \______   \ ____   ____ |  | _\_ |__   _______  ___
 *   Source     |       _//  _ \_/ ___\|  |/ /| __ \ /  _ \  \/  /
 *   Jukebox    |    |   (  <_> )  \___|    < | \_\ (  <_> > <  <
 *   Firmware   |____|_  /\____/ \___  >__|_ \|___  /\____/__/\_ \
 *                     \/            \/     \/    \/            \/
 * $Id$
 *
 * Copyright (C) 2007 by Bj�rn Stenberg
 *
 * 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 2
 * of the License, or (at your option) any later version.
 *
 * This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY
 * KIND, either express or implied.
 *
 ****************************************************************************/
#include "system.h"
#include "thread.h"
#include "kernel.h"
#include "string.h"
//#define LOGF_ENABLE
#include "logf.h"

#include "usb.h"
#include "usb_ch9.h"
#include "usb_drv.h"
#include "usb_core.h"
#include "usb_class_driver.h"

#if defined(USB_STORAGE)
#include "usb_storage.h"
#endif

#if defined(USB_SERIAL)
#include "usb_serial.h"
#endif

#if defined(USB_CHARGING_ONLY)
#include "usb_charging_only.h"
#endif

/* TODO: Move target-specific stuff somewhere else (serial number reading) */

#ifdef HAVE_AS3514
#include "ascodec.h"
#include "as3514.h"
#endif

#if !defined(HAVE_AS3514) && !defined(IPOD_ARCH) && (CONFIG_STORAGE & STORAGE_ATA)
#include "ata.h"
#endif

#ifndef USB_MAX_CURRENT
#define USB_MAX_CURRENT 500
#endif

/*-------------------------------------------------------------------------*/
/* USB protocol descriptors: */

#define USB_SC_SCSI      0x06            /* Transparent */
#define USB_PROT_BULK    0x50            /* bulk only */

static const struct usb_device_descriptor __attribute__((aligned(2)))
                                          device_descriptor=
{
    .bLength            = sizeof(struct usb_device_descriptor),
    .bDescriptorType    = USB_DT_DEVICE,
#ifndef USB_NO_HIGH_SPEED
    .bcdUSB             = 0x0200,
#else
    .bcdUSB             = 0x0110,
#endif
    .bDeviceClass       = USB_CLASS_PER_INTERFACE,
    .bDeviceSubClass    = 0,
    .bDeviceProtocol    = 0,
    .bMaxPacketSize0    = 64,
    .idVendor           = USB_VENDOR_ID,
    .idProduct          = USB_PRODUCT_ID,
    .bcdDevice          = 0x0100,
    .iManufacturer      = 1,
    .iProduct           = 2,
    .iSerialNumber      = 3,
    .bNumConfigurations = 1
} ;

static struct usb_config_descriptor __attribute__((aligned(2)))
                                    config_descriptor = 
{
    .bLength             = sizeof(struct usb_config_descriptor),
    .bDescriptorType     = USB_DT_CONFIG,
    .wTotalLength        = 0, /* will be filled in later */
    .bNumInterfaces      = 1,
    .bConfigurationValue = 1,
    .iConfiguration      = 0,
    .bmAttributes        = USB_CONFIG_ATT_ONE | USB_CONFIG_ATT_SELFPOWER,
    .bMaxPower           = (USB_MAX_CURRENT+1) / 2, /* In 2mA units */
};


static const struct usb_qualifier_descriptor __attribute__((aligned(2)))
                                             qualifier_descriptor =
{
    .bLength            = sizeof(struct usb_qualifier_descriptor),
    .bDescriptorType    = USB_DT_DEVICE_QUALIFIER,
    .bcdUSB             = 0x0200,
    .bDeviceClass       = 0,
    .bDeviceSubClass    = 0,
    .bDeviceProtocol    = 0,
    .bMaxPacketSize0    = 64,
    .bNumConfigurations = 1
};

static const struct usb_string_descriptor __attribute__((aligned(2)))
                                    usb_string_iManufacturer =
{
    24,
    USB_DT_STRING,
    {'R','o','c','k','b','o','x','.','o','r','g'}
};

static const struct usb_string_descriptor __attribute__((aligned(2)))
                                    usb_string_iProduct =
{
    42,
    USB_DT_STRING,
    {'R','o','c','k','b','o','x',' ',
     'm','e','d','i','a',' ',
     'p','l','a','y','e','r'}
};

static struct usb_string_descriptor __attribute__((aligned(2)))
                                    usb_string_iSerial =
{
    84,
    USB_DT_STRING,
    {'0','0','0','0','0','0','0','0','0','0','0','0','0','0','0','0',
     '0','0','0','0','0','0','0','0','0','0','0','0','0','0','0','0',
     '0','0','0','0','0','0','0','0','0'}
};

/* Generic for all targets */

/* this is stringid #0: languages supported */
static const struct usb_string_descriptor __attribute__((aligned(2)))
                                    lang_descriptor =
{
    4,
    USB_DT_STRING,
    {0x0409} /* LANGID US English */
};

static const struct usb_string_descriptor* const usb_strings[] =
{
   &lang_descriptor,
   &usb_string_iManufacturer,
   &usb_string_iProduct,
   &usb_string_iSerial
};

static int usb_address = 0;
static bool initialized = false;
static enum { DEFAULT, ADDRESS, CONFIGURED } usb_state;

static int usb_core_num_interfaces;

typedef void (*completion_handler_t)(int ep,int dir, int status, int length);
typedef bool (*control_handler_t)(struct usb_ctrlrequest* req);

static struct
{
    completion_handler_t completion_handler[2];
    control_handler_t control_handler[2];
    struct usb_transfer_completion_event_data completion_event;
} ep_data[USB_NUM_ENDPOINTS];

static struct usb_class_driver drivers[USB_NUM_DRIVERS] =
{
#ifdef USB_STORAGE
    [USB_DRIVER_MASS_STORAGE] = {
        .enabled = false,
        .needs_exclusive_storage = true,
        .first_interface = 0,
        .last_interface = 0,
        .request_endpoints = usb_storage_request_endpoints,
        .set_first_interface = usb_storage_set_first_interface,
        .get_config_descriptor = usb_storage_get_config_descriptor,
        .init_connection = usb_storage_init_connection,
        .init = usb_storage_init,
        .disconnect = usb_storage_disconnect,
        .transfer_complete = usb_storage_transfer_complete,
        .control_request = usb_storage_control_request,
#ifdef HAVE_HOTSWAP
        .notify_hotswap = usb_storage_notify_hotswap,
#endif
    },
#endif
#ifdef USB_SERIAL
    [USB_DRIVER_SERIAL] = {
        .enabled = false,
        .needs_exclusive_storage = false,
        .first_interface = 0,
        .last_interface = 0,
        .request_endpoints = usb_serial_request_endpoints,
        .set_first_interface = usb_serial_set_first_interface,
        .get_config_descriptor = usb_serial_get_config_descriptor,
        .init_connection = usb_serial_init_connection,
        .init = usb_serial_init,
        .disconnect = usb_serial_disconnect,
        .transfer_complete = usb_serial_transfer_complete,
        .control_request = usb_serial_control_request,
#ifdef HAVE_HOTSWAP
        .notify_hotswap = NULL,
#endif
    },
#endif
#ifdef USB_CHARGING_ONLY
    [USB_DRIVER_CHARGING_ONLY] = {
        .enabled = false,
        .needs_exclusive_storage = false,
        .first_interface = 0,
        .last_interface = 0,
        .request_endpoints = usb_charging_only_request_endpoints,
        .set_first_interface = usb_charging_only_set_first_interface,
        .get_config_descriptor = usb_charging_only_get_config_descriptor,
        .init_connection = NULL,
        .init = NULL,
        .disconnect = NULL,
        .transfer_complete = NULL,
        .control_request = NULL,
#ifdef HAVE_HOTSWAP
        .notify_hotswap = NULL,
#endif
    },
#endif
};

static void usb_core_control_request_handler(struct usb_ctrlrequest* req);

static unsigned char response_data[256] USB_DEVBSS_ATTR;


static short hex[16] = {'0','1','2','3','4','5','6','7',
                        '8','9','A','B','C','D','E','F'};
#ifdef IPOD_ARCH
static void set_serial_descriptor(void)
{
#ifdef IPOD_VIDEO
    uint32_t* serial = (uint32_t*)(0x20004034);
#else
    uint32_t* serial = (uint32_t*)(0x20002034);
#endif

    /* We need to convert from a little-endian 64-bit int
       into a utf-16 string of hex characters */
    short* p = &usb_string_iSerial.wString[24];
    uint32_t x;
    int i,j;

    for (i = 0; i < 2; i++) {
       x = serial[i];
       for (j=0;j<8;j++) {
          *p-- = hex[x & 0xf];
          x >>= 4;
       }
    }
    usb_string_iSerial.bLength=52;
}
#elif defined(HAVE_AS3514)
static void set_serial_descriptor(void)
{
    unsigned char serial[16];
    /* Align 32 digits right in the 40-digit serial number */
    short* p = &usb_string_iSerial.wString[1];
    int i;

    ascodec_readbytes(AS3514_UID_0, 0x10, serial);
    for (i = 0; i < 16; i++) {
        *p++ = hex[(serial[i] >> 4) & 0xF];
        *p++ = hex[(serial[i] >> 0) & 0xF];
    }
    usb_string_iSerial.bLength=68;
}
#elif (CONFIG_STORAGE & STORAGE_ATA)
/* If we don't know the device serial number, use the one
 * from the disk */
static void set_serial_descriptor(void)
{
    short* p = &usb_string_iSerial.wString[1];
    unsigned short* identify = ata_get_identify();
    unsigned short x;
    int i;

    for (i = 10; i < 20; i++) {
       x = identify[i];
       *p++ = hex[(x >> 12) & 0xF];
       *p++ = hex[(x >> 8) & 0xF];
       *p++ = hex[(x >> 4) & 0xF];
       *p++ = hex[(x >> 0) & 0xF];
    }
    usb_string_iSerial.bLength=84;
}
#elif (CONFIG_STORAGE & STORAGE_RAMDISK)
/* This "serial number" isn't unique, but it should never actually
   appear in non-testing use */
static void set_serial_descriptor(void)
{
    short* p = &usb_string_iSerial.wString[1];
    int i;
    for (i = 0; i < 16; i++) {
        *p++ = hex[(2*i)&0xF];
        *p++ = hex[(2*i+1)&0xF];
    }
    usb_string_iSerial.bLength=68;
}
#else
#warning No proper set_serial_descriptor() implementation for this target
static void set_serial_descriptor(void)
{
    short* p = &usb_string_iSerial.wString[1];
    int i;
    for (i = 0; i < 16; i++) {
        *p++ = hex[(2*i)&0xF];
        *p++ = hex[(2*i+1)&0xF];
    }
    usb_string_iSerial.bLength=68;
}
#endif

void usb_core_init(void)
{
    int i;
    if (initialized)
        return;

    usb_drv_init();

    /* class driver init functions should be safe to call even if the driver
     * won't be used. This simplifies other logic (i.e. we don't need to know
     * yet which drivers will be enabled */
    for(i=0;i<USB_NUM_DRIVERS;i++) {
        if(drivers[i].enabled && drivers[i].init != NULL)
            drivers[i].init();
    }

    initialized = true;
    usb_state = DEFAULT;
    logf("usb_core_init() finished");
}

void usb_core_exit(void)
{
    int i;
    for(i=0;i<USB_NUM_DRIVERS;i++) {
        if(drivers[i].enabled && drivers[i].disconnect != NULL)
        {
            drivers[i].disconnect ();
            drivers[i].enabled = false;
        }
    }

    if (initialized) {
        usb_drv_exit();
    }
    initialized = false;
    usb_state = DEFAULT;
    logf("usb_core_exit() finished");
}

void usb_core_handle_transfer_completion(
              struct usb_transfer_completion_event_data* event)
{
    int ep = event->endpoint;

    switch(ep) {
        case EP_CONTROL:
            logf("ctrl handled %ld",current_tick);
            usb_core_control_request_handler(
                                    (struct usb_ctrlrequest*)event->data);
            break;
        default:
            if(ep_data[ep].completion_handler[event->dir>>7] != NULL)
                ep_data[ep].completion_handler[event->dir>>7](ep,event->dir,
                                              event->status,event->length);
            break;
    }
}

void usb_core_enable_driver(int driver,bool enabled)
{
    drivers[driver].enabled = enabled;
}

bool usb_core_driver_enabled(int driver)
{
    return drivers[driver].enabled;
}

bool usb_core_any_exclusive_storage(void)
{
    int i;
    for(i=0;i<USB_NUM_DRIVERS;i++) {
        if(drivers[i].enabled &&
           drivers[i].needs_exclusive_storage)
        {
            return true;
        }
    }

    return false;
}

#ifdef HAVE_HOTSWAP
void usb_core_hotswap_event(int volume,bool inserted)
{
    int i;
    for(i=0;i<USB_NUM_DRIVERS;i++) {
        if(drivers[i].enabled &&
           drivers[i].notify_hotswap!=NULL)
        {
            drivers[i].notify_hotswap(volume,inserted);
        }
    }
}
#endif

static void usb_core_set_serial_function_id(void)
{
    int id = 0;
    int i;
    for(i=0;i<USB_NUM_DRIVERS;i++) {
        if(drivers[i].enabled)
            id |= 1<<i;
    }
    usb_string_iSerial.wString[0] = hex[id];
}

int usb_core_request_endpoint(int dir, struct usb_class_driver *drv)
{
    int ret, ep;

    ret = usb_drv_request_endpoint(dir);

    if (ret == -1)
        return -1;

    ep = ret & 0x7f;
    dir = ret >> 7;

    ep_data[ep].completion_handler[dir] = drv->transfer_complete;
    ep_data[ep].control_handler[dir] = drv->control_request;

    return ret;
}

void usb_core_release_endpoint(int ep)
{
    int dir;

    usb_drv_release_endpoint(ep);

    dir = ep >> 7;
    ep &= 0x7f;

    ep_data[ep].completion_handler[dir] = NULL;
    ep_data[ep].control_handler[dir] = NULL;
}

static void allocate_interfaces_and_endpoints(void)
{
    int i;
    int interface=0;

    memset(ep_data,0,sizeof(ep_data));

    for (i = 0; i < USB_NUM_ENDPOINTS; i++) {
        usb_drv_release_endpoint(i | USB_DIR_OUT);
        usb_drv_release_endpoint(i | USB_DIR_IN);
    }

    for(i=0; i < USB_NUM_DRIVERS; i++) {
        if(drivers[i].enabled) {
            drivers[i].first_interface = interface;

            if (drivers[i].request_endpoints(&drivers[i])) {
                drivers[i].enabled = false;
                continue;
            }

            interface = drivers[i].set_first_interface(interface);
            drivers[i].last_interface = interface;
        }
    }
    usb_core_num_interfaces = interface;
}

static void usb_core_control_request_handler(struct usb_ctrlrequest* req)
{
    int i;
    if(usb_state == DEFAULT) {
        set_serial_descriptor();
        usb_core_set_serial_function_id();

        allocate_interfaces_and_endpoints();
    }

    switch(req->bRequestType & 0x1f) {
        case 0: /* Device */
            switch (req->bRequest) {
                case USB_REQ_GET_CONFIGURATION: {
                    logf("usb_core: GET_CONFIG");
                    if (usb_state == ADDRESS)
                        response_data[0] = 0;
                    else
                        response_data[0] = 1;
                    if(usb_drv_send(EP_CONTROL, response_data, 1)!= 0)
                        break;
                    usb_core_ack_control(req);
                    break;
                case USB_REQ_SET_CONFIGURATION:
                    logf("usb_core: SET_CONFIG");
                    usb_drv_cancel_all_transfers();
                    if (req->wValue) {
                        usb_state = CONFIGURED;
                        for(i=0;i<USB_NUM_DRIVERS;i++) {
                            if(drivers[i].enabled &&
                               drivers[i].init_connection!=NULL)
                            {
                                drivers[i].init_connection();
                            }
                        }
                    }
                    else {
                        usb_state = ADDRESS;
                    }
                    usb_core_ack_control(req);
                    break;
                }
                case USB_REQ_SET_ADDRESS: {
                    unsigned char address = req->wValue;
                    logf("usb_core: SET_ADR %d", address);
                    if(usb_core_ack_control(req)!=0)
                        break;
                    usb_drv_cancel_all_transfers();
                    usb_address = address;
                    usb_drv_set_address(usb_address);
                    usb_state = ADDRESS;
                    break;
                }
                case USB_REQ_GET_DESCRIPTOR: {
                    int index = req->wValue & 0xff;
                    int length = req->wLength;
                    int size;
                    const void* ptr = NULL;
                    logf("usb_core: GET_DESC %d", req->wValue >> 8);

                    switch (req->wValue >> 8) { /* type */
                        case USB_DT_DEVICE:
                            ptr = &device_descriptor;
                            size = sizeof(struct usb_device_descriptor);
                            break;

                        case USB_DT_OTHER_SPEED_CONFIG:
                        case USB_DT_CONFIG: {
                            int max_packet_size;

                            if(req->wValue >> 8 == USB_DT_CONFIG) {
                                if(usb_drv_port_speed())
                                    max_packet_size=512;
                                else
                                    max_packet_size=64;
                                config_descriptor.bDescriptorType=USB_DT_CONFIG;
                            }
                            else {
                                if(usb_drv_port_speed())
                                    max_packet_size=64;
                                else
                                    max_packet_size=512;
                                config_descriptor.bDescriptorType =
                                                 USB_DT_OTHER_SPEED_CONFIG;
                            }
                            size = sizeof(struct usb_config_descriptor);

                            for(i=0;i<USB_NUM_DRIVERS;i++) {
                                if(drivers[i].enabled &&
                                   drivers[i].get_config_descriptor)
                                {
                                    size+=drivers[i].get_config_descriptor(
                                             &response_data[size],
                                             max_packet_size);
                                }
                            }
                            config_descriptor.bNumInterfaces =
                                                     usb_core_num_interfaces;
                            config_descriptor.wTotalLength = size;
                            memcpy(&response_data[0],&config_descriptor,
                                   sizeof(struct usb_config_descriptor));

                            ptr = response_data;
                            break;
                        }

                        case USB_DT_STRING:
                            logf("STRING %d",index);
                            if ((unsigned)index < (sizeof(usb_strings)/
                                         sizeof(struct usb_string_descriptor*)))
                            {
                                size = usb_strings[index]->bLength;
                                ptr = usb_strings[index];
                            }
                            else {
                                logf("bad string id %d", index);
                                usb_drv_stall(EP_CONTROL, true,true);
                            }
                            break;

                        case USB_DT_DEVICE_QUALIFIER:
                            ptr = &qualifier_descriptor;
                            size = sizeof (struct usb_qualifier_descriptor);
                            break;

                        default:
                            logf("bad desc %d", req->wValue >> 8);
                            usb_drv_stall(EP_CONTROL, true,true);
                            break;
                    }

                    if (ptr) {
                        length = MIN(size, length);

                        if (ptr != response_data) {
                            memcpy(response_data, ptr, length);
                        }

                        if(usb_drv_send(EP_CONTROL, response_data, length)!=0)
                            break;
                    }
                    usb_core_ack_control(req);
                    break;
                } /* USB_REQ_GET_DESCRIPTOR */
                case USB_REQ_CLEAR_FEATURE:
                    break;
                case USB_REQ_SET_FEATURE:
                    if(req->wValue == 2) { /* TEST_MODE */
                        int mode=req->wIndex>>8;
                        usb_core_ack_control(req);
                        usb_drv_set_test_mode(mode);
                    }
                    break;
                case USB_REQ_GET_STATUS:
                    response_data[0]= 0;
                    response_data[1]= 0;
                    if(usb_drv_send(EP_CONTROL, response_data, 2)!=0)
                        break;
                    usb_core_ack_control(req);
                    break;
                default:
                    break;
            }
            break;
        case 1: /* Interface */
            switch (req->bRequest) {
                case USB_REQ_SET_INTERFACE:
                    logf("usb_core: SET_INTERFACE");
                    usb_core_ack_control(req);
                    break;

                case USB_REQ_GET_INTERFACE:
                    logf("usb_core: GET_INTERFACE");
                    response_data[0] = 0;
                    if(usb_drv_send(EP_CONTROL, response_data, 1)!=0)
                        break;
                    usb_core_ack_control(req);
                    break;
                case USB_REQ_CLEAR_FEATURE:
                    break;
                case USB_REQ_SET_FEATURE:
                    break;
                case USB_REQ_GET_STATUS:
                    response_data[0]= 0;
                    response_data[1]= 0;
                    if(usb_drv_send(EP_CONTROL, response_data, 2)!=0)
                        break;
                    usb_core_ack_control(req);
                    break;
                default: {
                    bool handled=false;
                    for(i=0;i<USB_NUM_DRIVERS;i++) {
                        if(drivers[i].enabled &&
                           drivers[i].control_request &&
                           drivers[i].first_interface <= (req->wIndex) &&
                           drivers[i].last_interface > (req->wIndex))
                        {
                            handled = drivers[i].control_request(req);
                        }
                    }
                    if(!handled) {
                        /* nope. flag error */
                        logf("usb bad req %d", req->bRequest);
                        usb_drv_stall(EP_CONTROL, true,true);
                        usb_core_ack_control(req);
                    }
                    break;
                }
            }
            break;
        case 2: /* Endpoint */
            switch (req->bRequest) {
                case USB_REQ_CLEAR_FEATURE:
                    if (req->wValue == 0 ) /* ENDPOINT_HALT */
                        usb_drv_stall(req->wIndex & 0xf, false,
                                      (req->wIndex & 0x80) !=0);
                    usb_core_ack_control(req);
                    break;
                case USB_REQ_SET_FEATURE:
                    if (req->wValue == 0 ) /* ENDPOINT_HALT */
                        usb_drv_stall(req->wIndex & 0xf, true,
                                      (req->wIndex & 0x80) !=0);
                    usb_core_ack_control(req);
                    break;
                case USB_REQ_GET_STATUS:
                    response_data[0]= 0;
                    response_data[1]= 0;
                    logf("usb_core: GET_STATUS"); 
                    if(req->wIndex>0)
                        response_data[0] = usb_drv_stalled(req->wIndex&0xf,
                                                       (req->wIndex&0x80)!=0);
                    if(usb_drv_send(EP_CONTROL, response_data, 2)!=0)
                        break;
                    usb_core_ack_control(req);
                    break;
                default: {
                    bool handled=false;
                    if(ep_data[req->wIndex & 0xf].control_handler[0] != NULL)
                        handled = ep_data[req->wIndex & 0xf].control_handler[0](req);
                    if(!handled) {
                        /* nope. flag error */
                        logf("usb bad req %d", req->bRequest);
                        usb_drv_stall(EP_CONTROL, true,true);
                        usb_core_ack_control(req);
                    }
                    break;
                }
            }
    }
    logf("control handled");
}

/* called by usb_drv_int() */
void usb_core_bus_reset(void)
{
    usb_address = 0;
    usb_state = DEFAULT;
}

/* called by usb_drv_transfer_completed() */
void usb_core_transfer_complete(int endpoint, int dir, int status,int length)
{
    switch (endpoint) {
        case EP_CONTROL:
            /* already handled */
            break;

        default:
            ep_data[endpoint].completion_event.endpoint=endpoint;
            ep_data[endpoint].completion_event.dir=dir;
            ep_data[endpoint].completion_event.data=0;
            ep_data[endpoint].completion_event.status=status;
            ep_data[endpoint].completion_event.length=length;
            /* All other endoints. Let the thread deal with it */
            usb_signal_transfer_completion(&ep_data[endpoint].completion_event);
            break;
    }
}

/* called by usb_drv_int() */
void usb_core_control_request(struct usb_ctrlrequest* req)
{
    ep_data[0].completion_event.endpoint=0;
    ep_data[0].completion_event.dir=0;
    ep_data[0].completion_event.data=(void *)req;
    ep_data[0].completion_event.status=0;
    ep_data[0].completion_event.length=0;
    logf("ctrl received %ld",current_tick);
    usb_signal_transfer_completion(&ep_data[0].completion_event);
}

int usb_core_ack_control(struct usb_ctrlrequest* req)
{
    if (req->bRequestType & 0x80)
        return usb_drv_recv(EP_CONTROL, NULL, 0);
    else
        return usb_drv_send(EP_CONTROL, NULL, 0);
}

#ifdef HAVE_USB_POWER
unsigned short usb_allowed_current()
{
    if (usb_state == CONFIGURED)
    {
        return MAX(USB_MAX_CURRENT, 100);
    }
    else
    {
        return 100;
    }
}
#endif