rdb_slave.c 22.9 KB
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 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 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840
/*---------------------------------------------------------------------*
 *  Copyright (C) 2003 BroadOn Communications Corp.
 *                 
 *  $RCSfile: rdb_slave.c,v $
 *  $Revision: 1.37 $
 *  $Date: 2004/10/08 22:32:43 $
 *---------------------------------------------------------------------*/

/*
 * USB slave RDB driver
 *
 * This driver provides a data pipe between the host and the
 * BB over which RDB protocol packets are passed in both directions.
 * This allows RDB to be used to debug libultra apps on a BBPLAYER
 * using a PC host connected to the BB using a standard USB CAT-A
 * to Mini-B cable.
 */

#include "osint.h"
#include "host.h"
#include "device.h"
#include "rdb.h"
#include "os_message.h"
#include "os_bb.h"

#define DCACHE_ALIGN	__attribute__ ((aligned (16)))

#define  CONTROL_MAX_PKT_SIZE          (64)
#define  INTR_MAX_PKT_SIZE             (64)
#define  BULK_MAX_PKT_SIZE             (64)

/* Endpoint numbers */
#define BULK_RDB_EP 2
#define BULK_RDB_OUT_EP	BULK_RDB_EP
#define BULK_RDB_IN_EP	BULK_RDB_EP

#define RDBS_VENDOR_ID 0x1527	/* official USB Vendor ID */
//#define RDBS_VENDOR_ID 0xBB3D	/* unofficial Vendor ID */
#define RDBS_PRODUCT_ID 0xBBDB
#define RDBS_VERSION_ID 0x0001

/* Device descriptors are always 18 bytes */
static uint_8  DevDesc[18] =
{
   /* Length of DevDesc */
   sizeof(DevDesc),
   /* "Device" Type of descriptor */
   1,
   /* BCD USB version */
   USB_uint_16_low(0x0110), USB_uint_16_high(0x0110),
   /* Device Class is indicated in the interface descriptors */
   0x00,
   /* Device Subclass is indicated in the interface descriptors */
   0x00,
   /* RDB device does not use class-specific protocols */
   0x00,
   /* Max packet size */
   CONTROL_MAX_PKT_SIZE,
   /* Vendor ID */
   USB_uint_16_low(RDBS_VENDOR_ID), USB_uint_16_high(RDBS_VENDOR_ID),
   /* Product ID */
   USB_uint_16_low(RDBS_PRODUCT_ID), USB_uint_16_high(RDBS_PRODUCT_ID),
   /* BCD Device version */
   USB_uint_16_low(RDBS_VERSION_ID), USB_uint_16_high(RDBS_VERSION_ID),
   /* Manufacturer string index */
   0x1,
   /* Product string index */
   0x2,
   /* Serial number string index */
   0x0,
   /* Number of configurations available */
   0x1
};

#define CONFIG_DESC_NUM_INTERFACES  (4)
/* This must be counted manually and updated with the descriptor */
/* 1*Config(9) + 1*Interface(9) + 2*Endpoint(7) = 32 bytes */
#define CONFIG_DESC_SIZE            (32)

static uint_8 ConfigDesc[CONFIG_DESC_SIZE] =
{
   /* Configuration Descriptor - always 9 bytes */
   9,
   /* "Configuration" type of descriptor */
   2,
   /* Total length of the Configuration descriptor */
   USB_uint_16_low(CONFIG_DESC_SIZE), USB_uint_16_high(CONFIG_DESC_SIZE),
   /* NumInterfaces */
   1,
   /* Configuration Value */
   1,
   /* Configuration Description String Index */
   0,
   /* Attributes:  Bus-powered */
   0x80,
   /* Current draw from bus == 500mA (units of 2mA) */
   250,
   /* ----------------- Interfaces ------------------ */
   /* Interface 0 Descriptor - always 9 bytes */
   9,
   /* "Interface" type of descriptor */
   4,
   /* Number of this interface */
   0,
   /* Alternate Setting */
   0,
   /* Number of endpoints on this interface */
   2,
   /* Interface Class: Vendor specific */
   0xFF,
   /* Interface Subclass: Vendor specific */
   0xFF,
   /* Interface Protocol: standard RDB protocol */
   0x0,
   /* Interface Description String Index */
   0,
   /* ----------------- Endpoints ------------------ */
   /* -- Endpoint 3 (Bulk In), Interface 0 Descriptor - always 7 bytes*/
   7,
   /* "Endpoint" type of descriptor */
   5,
   /*
   ** Endpoint address.  The low nibble contains the endpoint number and the
   ** high bit indicates TX(1) or RX(0).
   */
   0x82,
   /* Attributes.  0=Control 1=Isochronous 2=Bulk 3=Interrupt */
   0x02,
   /* Max Packet Size for this endpoint */
   USB_uint_16_low(BULK_MAX_PKT_SIZE), 
   USB_uint_16_high(BULK_MAX_PKT_SIZE),
   /* Polling Interval (ms) */
   0,
   /* -- Endpoint 4 (Bulk Out), Interface 0 Descriptor - always 7 bytes*/
   7,
   /* "Endpoint" type of descriptor */
   5,
   /*
   ** Endpoint address.  The low nibble contains the endpoint number and the
   ** high bit indicates TX(1) or RX(0).
   */
   0x02,
   /* Attributes.  0=Control 1=Isochronous 2=Bulk 3=Interrupt */
   0x02,
   /* Max Packet Size for this endpoint */
   USB_uint_16_low(BULK_MAX_PKT_SIZE), 
   USB_uint_16_high(BULK_MAX_PKT_SIZE),
   /* Polling Interval (ms) */
   0,
};

/* number of strings in the table not including 0 or n. */
#define USB_STR_NUM	2

/*
** if the number of strings changes, look for USB_STR_0 everywhere and make 
** the obvious changes.  It should be found in 3 places.
*/

/* Languages supported = American English (0x0409) */
static uint_8 USB_STR_0[ 4] = {sizeof(USB_STR_0), 0x03, 0x09, 0x04};
static uint_8 USB_STR_1[20] = {sizeof(USB_STR_1), 0x03,
      'i',0,'Q',0,'u',0,'e',0,' ',0,'L',0,'t',0,'d',0,	/* 16 chars per row */
      '.',0};
static uint_8 USB_STR_2[24] = {sizeof(USB_STR_2), 0x03,
      'i',0,'Q',0,'u',0,'e',0,' ',0,'P',0,'l',0,'a',0,
      'y',0,'e',0,'r',0};
static uint_8 USB_STR_n[34] = {sizeof(USB_STR_n), 0x03,
      'B',0,'A',0,'D',0,' ',0,'S',0,'T',0,'R',0,'I',0,
      'N',0,'G',0,' ',0,'I',0,'n',0,'d',0,'e',0,'x',0};

static const uint_8_ptr USB_STRING_DESC[USB_STR_NUM+2] =
{
   (uint_8_ptr)USB_STR_0,
   (uint_8_ptr)USB_STR_1,
   (uint_8_ptr)USB_STR_2,
   (uint_8_ptr)USB_STR_n
};

/*
 * The RDB device supports 2 endpoints:
 * 
 * 	2 bulk endpoints (one each direction) for large transfers (loading
 * 	programs and the like)
 */

static boolean	rdbs_bulk_enabled;
static s32 rdbs_bulk_outlen;
static s32 rdbs_bulk_outpending;


#define	RIP_BULK_BUFSZ	20*1024	/* bulk buffer size for each direction */

static uchar in_bulk_buf0[RIP_BULK_BUFSZ] DCACHE_ALIGN;
static uchar in_bulk_buf1[RIP_BULK_BUFSZ] DCACHE_ALIGN;
static int cur_inbuf = 0;
struct {
    uchar *buf;
    int len;	/* amount of valid data after io complete */
} inbuf[2] = { { in_bulk_buf0, 0 }, {in_bulk_buf1, 0 } };

static uchar out_bulk_buf[RIP_BULK_BUFSZ] DCACHE_ALIGN;

static void rdbs_service_bulk_ep(_usb_device_handle, boolean, uint_8, uint_8_ptr, uint_32); 

#if !defined(_FINALROM)
extern rdbPacket *__osRdb_IP6_Data;
extern u32    __osRdb_IP6_Empty;
extern u32    __osRdb_IP6_Size;
extern u32    __osRdb_IP6_Ct;
extern u32    __osRdb_IP6_CurWrite;
extern u32    __osRdb_IP6_CurSend;
extern u8    *__osRdb_Read_Data_Buf;
extern u32    __osRdb_Read_Data_Ct;
#ifdef _DEBUG
       u8    *__osRdb_DbgRead_Buf = NULL;
       u32    __osRdb_DbgRead_BufSize = 0;
       u32    __osRdb_DbgRead_Ct = 0; 
       u32    __osRdb_DbgRead_Err = 0;
#endif	/* _DEBUG */

#define ES_SIZE	8	/* size of entry in the Event State table */
extern void   send_mesg(int);

static _usb_device_handle rdb_device_handle;

extern void (*__osRdb_Usb_StartSend)(void *datap, int len);

/* Returns number of bytes available in the RDB USB send buffer */
u32 __osRdb_Usb_GetAvailSendBytes()
{
    return RIP_BULK_BUFSZ - rdbs_bulk_outlen;
}

/*
 * Torque converters for USB RDB to the libultra IP6 RDB mechanisms
 * Copies data from the input datap (first RDB packet) and also 
 * anything from __OsRdb_IP6_Data (queued out RDB packets) into the 
 * out_bulk_buf, which is then posted to the USB device for sending.
 * 
 * NOTE: This functions only prepares the data to be sent, when
 *       it returns, some of the data may still be queued in
 *       the __osRdb_IP6_Data and in the USB device.
 *       If the amount of the data in datap is too large (i.e.
 *       greater than the available space in out_bulk_buf)
 *       then the overflow data is discarded.
 *
 * REVIEW: What if USB is not completely set up yet?
 *         Should we check rdbs_bulk_enabled = TRUE?
 */
static void
osRdb_Usb_StartSend(void *datap, int len)
{
	int dlen;
	rdbPacket *pktp;

	USB_lock();

	/*
	 * The argument points to the first RDB packet, but there
	 * may be more queued up to send
	 */
	dlen = MIN(len, RIP_BULK_BUFSZ - rdbs_bulk_outlen);
	if (dlen > 0) {
		if ((rdbs_bulk_outlen & 0x3) || ((unsigned)datap & 0x3)) {
		    bcopy((void *)datap, &out_bulk_buf[rdbs_bulk_outlen], dlen);
		} else {
		    pktp = (rdbPacket *) &out_bulk_buf[rdbs_bulk_outlen];
		    *pktp = *(rdbPacket *) datap;
		}
		rdbs_bulk_outlen += dlen;
		len -= dlen;
		if (len > 0) {
			goto out;
        	}
	}

    /* 
     * Copies queued data from __osRdb_IP6_Data into out_bulk_buf
     * NOTE: The data has to be copied one entire RDB packet at a time
     *       to ensure that no RDB packet is split into two.  
     *       Also note the block data and debug RDB packets are only 
     *       from host to BB, so that all RDB packets sent from BB to 
     *       host are 4 bytes.
     */
	while (__osRdb_IP6_Ct > 0) {
		dlen = sizeof(rdbPacket);
		if (dlen > RIP_BULK_BUFSZ - rdbs_bulk_outlen) {
			goto out;
        	}

		if (rdbs_bulk_outlen & 0x3) {
		    /* use bcopy only if not correctly aligned */
		    bcopy((void *)&__osRdb_IP6_Data[__osRdb_IP6_CurSend],
			&out_bulk_buf[rdbs_bulk_outlen], dlen);
		} else {
		    pktp = (rdbPacket *) &out_bulk_buf[rdbs_bulk_outlen];
		    *pktp = __osRdb_IP6_Data[__osRdb_IP6_CurSend];
		}
		rdbs_bulk_outlen += dlen;
		__osRdb_IP6_Ct--;
		if (++__osRdb_IP6_CurSend >= __osRdb_IP6_Size) {
			__osRdb_IP6_CurSend = 0;
        	}
	}

out:
	/*
	 * if there is not already an output packet posted, start output
	 */
	if (rdbs_bulk_outpending == 0) {
		rdbs_service_bulk_ep(rdb_device_handle, 0, USB_SEND, NULL, 0);
        }
	
	/* tell __osRdbSend to start over */
	if (__osRdb_IP6_Ct == 0) {
		__osRdb_IP6_Empty = 1;
        }

	USB_unlock();
}
#endif /* !_FINALROM */

static void
rdb_ip6_input(_usb_device_handle handle)
{
#ifndef _FINALROM
	int cmd;
	int dlen;
	unsigned char *dp;
	unsigned char *buf;
	int other;
	int total;
	int len;
	int excess;
	int save_data_ct;
#ifdef _DEBUG
	int buflen;
#endif

	/*
	 * Double buffering:  the current buffer is posted for USB
	 * and the input to be processed is in the other one
	 */
	other = ~cur_inbuf & 1;
	len = inbuf[other].len;
	buf = inbuf[other].buf;

	/*
	 * The input data is in the form of RDB packets, most of
	 * which are 32 bits or less, except for HtoG_DATAB transfers
	 */
	total = 0;
        save_data_ct = __osRdb_Read_Data_Ct;

	/*
	 * Unpack the RDB packets according to the packet type
	 */
	while (len > 0) {
		int i;

		cmd = buf[total++];
		len--;			/* subtract cmd byte */
		dlen = cmd & 0x3;	/* extract length of data in this RDB packet */
		cmd >>= 2;		/* RDB packet type */

		switch (cmd) {
		case RDB_TYPE_HtoG_DATA:
            dp = __osRdb_Read_Data_Buf;
			if (dlen > __osRdb_Read_Data_Ct) {
				/* this is a protocol error */
				printf(">>rdb_ip6_input: DATA with len %d, expecting %d\n",
					   dlen, __osRdb_Read_Data_Ct);
				/* throw away the excess data */
				excess = dlen - __osRdb_Read_Data_Ct;
				dlen = __osRdb_Read_Data_Ct;
			} else 
                excess = 0;

			for (i = 0; i < dlen; i++)
				*dp++ = buf[total++];

			__osRdb_Read_Data_Ct -= dlen;
			__osRdb_Read_Data_Buf = dp;
			len -= dlen + excess;
			total += excess;
			break;

		case RDB_TYPE_HtoG_DATAB:
			/*
			 * New big block protocol for better throughput:
			 * ignore len in cmd byte, second byte is total length
			 */
            dp = __osRdb_Read_Data_Buf;
			dlen = buf[total++];
			len--;
			if (dlen > __osRdb_Read_Data_Ct) {
				/* this is a protocol error */
				/* throw away the excess data */
				excess = dlen - __osRdb_Read_Data_Ct;
				dlen = __osRdb_Read_Data_Ct;
			} else {
			       	excess = 0;
			}
			if (dlen > len) {
			    /*
			     * DATAB transaction is split across
			     * two USB receives?  This is a disaster,
			     * but what to do?
			     */
			}
			bcopy(&buf[total], dp, dlen);
			__osRdb_Read_Data_Ct -= dlen;
			dp += dlen;
			__osRdb_Read_Data_Buf = dp;
			len -= dlen + excess;
			total += dlen + excess;
			break;

		case RDB_TYPE_HtoG_DATA_DONE:
		case RDB_TYPE_HtoG_SYNC_DONE:
			/* wake up the thread in osWriteHost */
			send_mesg(OS_EVENT_RDB_DATA_DONE * ES_SIZE);
			total += dlen;
			len -= dlen;
			break;

#ifdef _DEBUG
		case RDB_TYPE_HtoG_DEBUG:
			/*
			 * Similar block protocol as for RDB_TYPE_HtoG_DATAB
			 * If dlen == 0, then ignore length in cmd byte, 
             *     second byte is total length
             * Otherwise, use dlen.
             * Assumes the RDB_TYPE_HtoG_DEBUG would never be
             *   sent with 0 bytes of data.
			 */

            /* We are currently inside a critical section (i.e. interrupts
               are disabled so we don't need to worry about shared 
               variables) */
            if ((dlen == 0) && (len > 0))
            {
                dlen = buf[total++];
                len--;
            }

            /* Set buffer to copy into */
			dp = __osRdb_DbgRead_Buf;

            if (dp == NULL)
            {
                /* RDB Debug not initialized - skip over packet */
                total += dlen;
                len -= dlen;
                break;
            }

            /* Double check length */
            if (len < dlen) 
            {
                /* ERROR: We are expecting dlen bytes of data, but there is not enough */
                __osRdb_DbgRead_Err++;
                printf(">>rdb_ip6_input: ERROR - Expected %d bytes for DEBUG stream,"
                       "only %d bytes remaining in RDB.\n", dlen, len);
                /* Well, let's just consume len bytes then */
                dlen = len;
            }

            /* Check Dbg buffer */
            buflen = __osRdb_DbgRead_BufSize - __osRdb_DbgRead_Ct;
            if (dlen > buflen)
            {
                __osRdb_DbgRead_Err++;
                /* We don't have enough space in the buffer 
                       Only copy buflen, ignore the rest */
                excess = dlen - buflen;
                dlen = buflen;
            } else {
                excess = 0;
            }
            
            /* Copy data */
            bcopy(&buf[total], dp, dlen);
            
            dp += dlen;
            __osRdb_DbgRead_Ct += dlen;
            __osRdb_DbgRead_Buf = dp;
            len -= dlen + excess;
            total += dlen + excess;
			break;

        case RDB_TYPE_HtoG_DEBUG_DONE:
			/* wake up the thread in gdbIOHandler */
			printf(">>rdb_ip6_input: wake up thread in gdbIOHandler\n");
			send_mesg(OS_EVENT_RDB_DBG_DONE * ES_SIZE);
			total += dlen;
			len -= dlen;
            break;
#endif	/* _DEBUG */

		default:
			printf(">>rdb_ip6_input: unknown type %d\n", cmd);
			len -= dlen;
			total += dlen;
			break;
		}
	}
	/*
	 * if we processed any read data and the input is now complete,
	 * wake up the reader thread in osReadHost
	 */
	if (__osRdb_Read_Data_Ct == 0 && save_data_ct != 0) {
		send_mesg(OS_EVENT_RDB_READ_DONE * ES_SIZE);
	}
#endif /* !_FINALROM */
}

/* 
 * rdbs_service_bulk_ep
 *
 * Callback to implement rdbs data functions for bulk data.
 */ 
static void
rdbs_service_bulk_ep
   (
      _usb_device_handle   handle,
      boolean              setup,
      uint_8               direction,
      uint_8_ptr           buffer,
      uint_32              length      
   )
{
	USB_lock();
	/*
	 * Process input and post another buffer
	 */
	if (direction == USB_RECV) {
		inbuf[cur_inbuf].len = length;
		/* post the other buffer */
                cur_inbuf = ~cur_inbuf & 1;
                _usb_device_recv_data(handle, BULK_RDB_IN_EP, 
              	    inbuf[cur_inbuf].buf, RIP_BULK_BUFSZ);
		/* call ip6 routine to deal with the new data */
		rdb_ip6_input(handle);
		USB_unlock();
		return;
	}

	if (direction == USB_SEND) {
		/*
		 * check if more data to send
		 */
		rdbs_bulk_outlen -= length;
		if (rdbs_bulk_outlen < 0) {
			/* XXX can this happen? */
			rdbs_bulk_outlen = 0;
		}
		if (rdbs_bulk_outlen > 0) {
			int outlen;

			if (length > 0)
				bcopy(&out_bulk_buf[length], out_bulk_buf, rdbs_bulk_outlen);
            		outlen = rdbs_bulk_outlen;
			/* don't send multiples of 64 bytes XXX */
			if ((outlen & 0x3f) == 0)
				outlen -= 4;
            		(void)_usb_device_send_data(handle, BULK_RDB_OUT_EP, out_bulk_buf, outlen);
		}
		rdbs_bulk_outpending = rdbs_bulk_outlen;
		/* 
		 * if output USB buffer is empty, there may be more RDB data
		 */
#ifndef _FINALROM
		if (rdbs_bulk_outlen == 0) {
			/*
			 * only do this when called from USB completion (length != 0)
			 */
			if (length != 0 && __osRdb_IP6_Ct > 0)
				osRdb_Usb_StartSend(NULL, 0);
		}
#endif
	}
	
	USB_unlock();
	return;
}

static char DevDescShort[8];

/*FUNCTION*----------------------------------------------------------------
* 
* Function Name  : ch9GetDescription
* Returned Value : None
* Comments       :
*     Chapter 9 GetDescription command
*     The Device Request can ask for Device/Config/string/interface/endpoint
*     descriptors (via wValue). We then post an IN response to return the
*     requested descriptor.
*     And then wait for the OUT which terminates the control transfer.
*     See section 9.4.3 (page 189) of the USB 1.1 Specification.
* 
*END*--------------------------------------------------------------------*/
static void rdbs_ch9GetDescription
   (
      _usb_device_handle handle,
      boolean setup,
      SETUP_STRUCT_PTR setup_ptr
   )
{
	uint_16 value;
	int len;

   if (setup) {
      /* Load the appropriate string depending on the descriptor requested.*/
      value = swab16(setup_ptr->VALUE) & 0xFF00;
      len = swab16(setup_ptr->LENGTH);

      switch (value) {

         case 0x0100:
	    if (len <= 8) {
		    bcopy((void *)&DevDesc, (void *)&DevDescShort[0], 8);
		    DevDescShort[0] = 8;
            	    _usb_device_send_data(handle, 0, (uchar_ptr)&DevDescShort[0], 8);
	    } else {
                    _usb_device_send_data(handle, 0, (uchar_ptr)&DevDesc,
                               MIN(len, sizeof(DevDesc)));
	    }
            break;

         case 0x0200:
            _usb_device_send_data(handle, 0, (uchar_ptr)&ConfigDesc,
               MIN(len, sizeof(ConfigDesc)));
            break;

         case 0x0300:
            value = swab16(setup_ptr->VALUE) & 0x00FF;
            if (value > USB_STR_NUM) {
               _usb_device_send_data(handle, 0, USB_STRING_DESC[USB_STR_NUM+1],
                  MIN(len, USB_STRING_DESC[USB_STR_NUM+1][0]));
            } else {
               _usb_device_send_data(handle, 0,
                  USB_STRING_DESC[value],
                  MIN(len, USB_STRING_DESC[value][0]));
            }
            break;

         default:
            _usb_device_stall_endpoint(handle, 0, 0);
            return;
      }
      /* status phase */
      _usb_device_recv_data(handle, 0, 0, 0);
      dev_global_struct.dev_state = USB_DEV_STATE_ATTACHED;
   }
   return;
}

static void
rdbs_init_data_eps(_usb_device_handle handle)
{
	uint_16 ep_num, max_pkt;
	uint_8 ep_type;
	int status;

    ep_num = BULK_RDB_EP;
    ep_type = USB_BULK_ENDPOINT;
    max_pkt = BULK_MAX_PKT_SIZE;
    _usb_device_init_endpoint(handle, ep_num, max_pkt, USB_RECV, ep_type, 0);
    _usb_device_init_endpoint(handle, ep_num, max_pkt, USB_SEND, ep_type, 0);
    _usb_device_register_service(handle, ep_num, rdbs_service_bulk_ep);
    status = _usb_device_get_transfer_status(handle, ep_num, USB_RECV);
	if (status != USB_STATUS_IDLE) {
		printf(">>>rdbs_init_eps: bulk recv already pending!\n");
	} else {
		printf(">>>rdbs_init_eps: post bulk recv buf for ep%d\n", ep_num);
		cur_inbuf = 0;
            	_usb_device_recv_data(handle, ep_num, inbuf[cur_inbuf].buf, RIP_BULK_BUFSZ);
        }
	rdbs_bulk_outlen = 0;
	rdbs_bulk_outpending = 0;
        rdbs_bulk_enabled = TRUE;
}

static void
rdbs_reset_data_eps(_usb_device_handle handle)
{
    uint_16 ep_num;

    ep_num = BULK_RDB_EP;
    _usb_device_cancel_transfer(handle, ep_num, USB_RECV);
    _usb_device_cancel_transfer(handle, ep_num, USB_SEND);
    //_usb_device_unregister_service(handle, ep_num);
    rdbs_bulk_outlen = 0;
    rdbs_bulk_outpending = 0;
    rdbs_bulk_enabled = FALSE;

    osResetRdb();

#ifndef _FINALROM
    /* Informs upper layer that the RDB endpoint is being reset */
    send_mesg(OS_EVENT_RDB_READ_RESET * ES_SIZE);
    send_mesg(OS_EVENT_RDB_DATA_RESET * ES_SIZE);
#endif
}

static void
rdbs_stall_data_eps(_usb_device_handle handle, uint_8 ep_num, boolean stall)
{
    if ((ep_num == BULK_RDB_EP) && (stall == 0)) {
        /* RDP endpoint unstalled - try to get it back into a known state */
        rdbs_reset_data_eps(handle);
        rdbs_init_data_eps(handle);
    }
}

/* 
 * rdbs_ch9Vendor
 *     Chapter 9 Vendor specific command
 *     Initialize non-control endpoints
 *     See section 9.4.11 (page 195) of the USB 1.1 Specification.
 */ 
void rdbs_ch9Vendor
   (
      _usb_device_handle handle,
      boolean setup,
      SETUP_STRUCT_PTR setup_ptr
   )
{
}

/*
 * 
 * rdbs_reset_ep0
 *     Called on a bus reset event.  Initializes the control endpoint.
 */
static void
rdbs_reset_ep0
   (
      /* [IN] Handle of the USB device */
      _usb_device_handle   handle,
   
      /* [IN] Unused */
      boolean              setup,
   
      /* [IN] Unused */
      uint_8               direction,
   
      /* [IN] Unused */
      uint_8_ptr           buffer,
   
      /* [IN] Unused */
      uint_32              length      
   )
{
   if (rdbs_bulk_enabled) {
       rdbs_reset_data_eps(handle);
   }
   
   _usb_device_init_endpoint(handle, 0, CONTROL_MAX_PKT_SIZE, 0,
         USB_CONTROL_ENDPOINT, 0);
   _usb_device_init_endpoint(handle, 0, CONTROL_MAX_PKT_SIZE, 1,
         USB_CONTROL_ENDPOINT, 0);

   return;
}

/*
 * Return info structure for the rdbs device.
 */
void
rdbs_query(OSBbUsbInfo *ip)
{
	ip->ua_type = OS_USB_TYPE_DEVICE;
	ip->ua_state = (dev_global_struct.dev_state == USB_DEV_STATE_ATTACHED) ? OS_USB_STATE_ATTACHED : OS_USB_STATE_NULL;
	ip->ua_class = 0;
	ip->ua_subclass = 0;
	ip->ua_protocol = 0;
	ip->ua_vendor = RDBS_VENDOR_ID;
	ip->ua_product = RDBS_PRODUCT_ID;
	ip->ua_cfg = 0;		/* XXX */
	ip->ua_ep = 1;		/* XXX */
	ip->ua_speed = OS_USB_FULL_SPEED;	/* XXX */
	ip->ua_mode = OS_USB_MODE_RW;	/* XXX */
	ip->ua_blksize = 64;
	ip->ua_mfr_str = "iQue Ltd";
#ifdef _FINALROM
	ip->ua_prod_str = "iQue Player (disabled)";
#else
	ip->ua_prod_str = "iQue Player";
#endif
	ip->ua_driver_name = "";
	ip->ua_support = TRUE;
}

#if !defined(_FINALROM)
extern u32 __osRdb_Usb_Active;
static u8 rdb_buffer[5472];	/* size needed to pack a 4096 byte block in RDB */
#endif

/*
 * Device-specific initialization for the rdb_slave device.
 */
void
rdbs_device_init(_usb_device_handle handle)
{
	dev_global_struct.num_ifcs = ConfigDesc[CONFIG_DESC_NUM_INTERFACES];
#if !defined(_FINALROM)
	/*
	 * Real RDB slave device provides the interface between the
	 * osReadHost/osWriteHost routines and the host, replacing
	 * the Indy/GIO solution and the IDE/PP solution on BB.
	 */

	/*
	 * If no-one else has called osInitRdb yet, do it here
	 */
	if (__osRdb_IP6_Data == NULL) {
		osInitRdb(rdb_buffer, sizeof rdb_buffer);
	}
	/*
	 * Set flag to force RDB to use USB
	 * XXX may need to be more discriminating about this
	 */
	__osRdb_Usb_Active = 1;	
	__osRdb_Usb_StartSend = osRdb_Usb_StartSend;
	rdb_device_handle = handle;
#endif
	return;
}

struct usbdevfuncs rdbs_dev_funcs = {
	rdbs_reset_ep0,
	rdbs_ch9GetDescription,
	rdbs_ch9Vendor,
	rdbs_init_data_eps,
	rdbs_query,
    rdbs_stall_data_eps
};