From 4189c40cb6666a5ec698dc7a5655f7b1b422a9ac Mon Sep 17 00:00:00 2001
From: Lukasz Majewski <l.majewski@samsung.com>
Date: Tue, 6 Nov 2012 09:59:11 +0100
Subject: [PATCH] UMS: CHanges made by Victor applied to UMS_v2 file applied to ML

---
 arch/arm/include/asm/bitops.h     |    4 +-
 drivers/usb/gadget/file_storage.c | 1073 ++++++++++++++++++++-----------------
 2 files changed, 582 insertions(+), 495 deletions(-)

diff --git a/arch/arm/include/asm/bitops.h b/arch/arm/include/asm/bitops.h
index b00ae30..ea951c4 100644
--- a/arch/arm/include/asm/bitops.h
+++ b/arch/arm/include/asm/bitops.h
@@ -25,9 +25,9 @@
 /*
  * Function prototypes to keep gcc -Wall happy.
  */
-extern void set_bit(int nr, void *addr);
+/* extern void set_bit(int nr, void *addr); */
 
-extern void clear_bit(int nr, void *addr);
+/* extern void clear_bit(int nr, void *addr); */
 
 extern void change_bit(int nr, void *addr);
 
diff --git a/drivers/usb/gadget/file_storage.c b/drivers/usb/gadget/file_storage.c
index d9b8635..afe178d 100644
--- a/drivers/usb/gadget/file_storage.c
+++ b/drivers/usb/gadget/file_storage.c
@@ -1,211 +1,205 @@
-/*
- * file_storage.c -- File-backed USB Storage Gadget, for USB development
- *
- * Copyright (C) 2003-2008 Alan Stern
- * All rights reserved.
- *
- * Ported to u-boot:
- * Andrzej Pietrasiewicz <andrzej.p@samsung.com>
- *
- * Code refactoring & cleanup:
- * ��ukasz Majewski <l.majewski@samsung.com>
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions
- * are met:
- * 1. Redistributions of source code must retain the above copyright
- *    notice, this list of conditions, and the following disclaimer,
- *    without modification.
- * 2. Redistributions in binary form must reproduce the above copyright
- *    notice, this list of conditions and the following disclaimer in the
- *    documentation and/or other materials provided with the distribution.
- * 3. The names of the above-listed copyright holders may not be used
- *    to endorse or promote products derived from this software without
- *    specific prior written permission.
- *
- * ALTERNATIVELY, this software may be distributed under the terms of the
- * GNU General Public License ("GPL") as published by the Free Software
- * Foundation, either version 2 of that License or (at your option) any
- * later version.
- *
- * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS
- * IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO,
- * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
- * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
- * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
- * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
- * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
- * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
- * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
- * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
- * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
- */
-
-
-/*
- * The File-backed Storage Gadget acts as a USB Mass Storage device,
- * appearing to the host as a disk drive or as a CD-ROM drive.  In addition
- * to providing an example of a genuinely useful gadget driver for a USB
- * device, it also illustrates a technique of double-buffering for increased
- * throughput.  Last but not least, it gives an easy way to probe the
- * behavior of the Mass Storage drivers in a USB host.
- *
- * Backing storage is provided by a regular file or a block device, specified
- * by the "file" module parameter.  Access can be limited to read-only by
- * setting the optional "ro" module parameter.  (For CD-ROM emulation,
- * access is always read-only.)  The gadget will indicate that it has
- * removable media if the optional "removable" module parameter is set.
- *
- * The gadget supports the Control-Bulk (CB), Control-Bulk-Interrupt (CBI),
- * and Bulk-Only (also known as Bulk-Bulk-Bulk or BBB) transports, selected
- * by the optional "transport" module parameter.  It also supports the
- * following protocols: RBC (0x01), ATAPI or SFF-8020i (0x02), QIC-157 (0c03),
- * UFI (0x04), SFF-8070i (0x05), and transparent SCSI (0x06), selected by
- * the optional "protocol" module parameter.  In addition, the default
- * Vendor ID, Product ID, release number and serial number can be overridden.
- *
- * There is support for multiple logical units (LUNs), each of which has
- * its own backing file.  The number of LUNs can be set using the optional
- * "luns" module parameter (anywhere from 1 to 8), and the corresponding
- * files are specified using comma-separated lists for "file" and "ro".
- * The default number of LUNs is taken from the number of "file" elements;
- * it is 1 if "file" is not given.  If "removable" is not set then a backing
- * file must be specified for each LUN.  If it is set, then an unspecified
- * or empty backing filename means the LUN's medium is not loaded.  Ideally
- * each LUN would be settable independently as a disk drive or a CD-ROM
- * drive, but currently all LUNs have to be the same type.  The CD-ROM
- * emulation includes a single data track and no audio tracks; hence there
- * need be only one backing file per LUN.  Note also that the CD-ROM block
- * length is set to 512 rather than the more common value 2048.
- *
- * Requirements are modest; only a bulk-in and a bulk-out endpoint are
- * needed (an interrupt-out endpoint is also needed for CBI).  The memory
- * requirement amounts to two 16K buffers, size configurable by a parameter.
- * Support is included for both full-speed and high-speed operation.
- *
- * Note that the driver is slightly non-portable in that it assumes a
- * single memory/DMA buffer will be useable for bulk-in, bulk-out, and
- * interrupt-in endpoints.  With most device controllers this isn't an
- * issue, but there may be some with hardware restrictions that prevent
- * a buffer from being used by more than one endpoint.
- *
- * Module options:
- *
- *	file=filename[,filename...]
- *				Required if "removable" is not set, names of
- *					the files or block devices used for
- *					backing storage
- *	ro=b[,b...]		Default false, booleans for read-only access
- *	removable		Default false, boolean for removable media
- *	luns=N			Default N = number of filenames, number of
- *					LUNs to support
- *	nofua=b[,b...]		Default false, booleans for ignore FUA flag
- *					in SCSI WRITE(10,12) commands
- *	stall			Default determined according to the type of
- *					USB device controller (usually true),
- *					boolean to permit the driver to halt
- *					bulk endpoints
- *	cdrom			Default false, boolean for whether to emulate
- *					a CD-ROM drive
- *	transport=XXX		Default BBB, transport name (CB, CBI, or BBB)
- *	protocol=YYY		Default SCSI, protocol name (RBC, 8020 or
- *					ATAPI, QIC, UFI, 8070, or SCSI;
- *					also 1 - 6)
- *	vendor=0xVVVV		Default 0x0525 (NetChip), USB Vendor ID
- *	product=0xPPPP		Default 0xa4a5 (FSG), USB Product ID
- *	release=0xRRRR		Override the USB release number (bcdDevice)
- *	serial=HHHH...		Override serial number (string of hex chars)
- *	buflen=N		Default N=16384, buffer size used (will be
- *					rounded down to a multiple of
- *					PAGE_CACHE_SIZE)
- *
- * If CONFIG_USB_FILE_STORAGE_TEST is not set, only the "file", "ro",
- * "removable", "luns", "nofua", "stall", and "cdrom" options are available;
- * default values are used for everything else.
- *
- * The pathnames of the backing files and the ro settings are available in
- * the attribute files "file", "nofua", and "ro" in the lun<n> subdirectory of
- * the gadget's sysfs directory.  If the "removable" option is set, writing to
- * these files will simulate ejecting/loading the medium (writing an empty
- * line means eject) and adjusting a write-enable tab.  Changes to the ro
- * setting are not allowed when the medium is loaded or if CD-ROM emulation
- * is being used.
- *
- * This gadget driver is heavily based on "Gadget Zero" by David Brownell.
- * The driver's SCSI command interface was based on the "Information
- * technology - Small Computer System Interface - 2" document from
- * X3T9.2 Project 375D, Revision 10L, 7-SEP-93, available at
- * <http://www.t10.org/ftp/t10/drafts/s2/s2-r10l.pdf>.  The single exception
- * is opcode 0x23 (READ FORMAT CAPACITIES), which was based on the
- * "Universal Serial Bus Mass Storage Class UFI Command Specification"
- * document, Revision 1.0, December 14, 1998, available at
- * <http://www.usb.org/developers/devclass_docs/usbmass-ufi10.pdf>.
- */
-
-
-/*
- *				Driver Design
- *
- * The FSG driver is fairly straightforward.  There is a main kernel
- * thread that handles most of the work.  Interrupt routines field
- * callbacks from the controller driver: bulk- and interrupt-request
- * completion notifications, endpoint-0 events, and disconnect events.
- * Completion events are passed to the main thread by wakeup calls.  Many
- * ep0 requests are handled at interrupt time, but SetInterface,
- * SetConfiguration, and device reset requests are forwarded to the
- * thread in the form of "exceptions" using SIGUSR1 signals (since they
- * should interrupt any ongoing file I/O operations).
- *
- * The thread's main routine implements the standard command/data/status
- * parts of a SCSI interaction.  It and its subroutines are full of tests
- * for pending signals/exceptions -- all this polling is necessary since
- * the kernel has no setjmp/longjmp equivalents.  (Maybe this is an
- * indication that the driver really wants to be running in userspace.)
- * An important point is that so long as the thread is alive it keeps an
- * open reference to the backing file.  This will prevent unmounting
- * the backing file's underlying filesystem and could cause problems
- * during system shutdown, for example.  To prevent such problems, the
- * thread catches INT, TERM, and KILL signals and converts them into
- * an EXIT exception.
- *
- * In normal operation the main thread is started during the gadget's
- * fsg_bind() callback and stopped during fsg_unbind().  But it can also
- * exit when it receives a signal, and there's no point leaving the
- * gadget running when the thread is dead.  So just before the thread
- * exits, it deregisters the gadget driver.  This makes things a little
- * tricky: The driver is deregistered at two places, and the exiting
- * thread can indirectly call fsg_unbind() which in turn can tell the
- * thread to exit.  The first problem is resolved through the use of the
- * REGISTERED atomic bitflag; the driver will only be deregistered once.
- * The second problem is resolved by having fsg_unbind() check
- * fsg->state; it won't try to stop the thread if the state is already
- * FSG_STATE_TERMINATED.
- *
- * To provide maximum throughput, the driver uses a circular pipeline of
- * buffer heads (struct fsg_buffhd).  In principle the pipeline can be
- * arbitrarily long; in practice the benefits don't justify having more
- * than 2 stages (i.e., double buffering).  But it helps to think of the
- * pipeline as being a long one.  Each buffer head contains a bulk-in and
- * a bulk-out request pointer (since the buffer can be used for both
- * output and input -- directions always are given from the host's
- * point of view) as well as a pointer to the buffer and various state
- * variables.
- *
- * Use of the pipeline follows a simple protocol.  There is a variable
- * (fsg->next_buffhd_to_fill) that points to the next buffer head to use.
- * At any time that buffer head may still be in use from an earlier
- * request, so each buffer head has a state variable indicating whether
- * it is EMPTY, FULL, or BUSY.  Typical use involves waiting for the
- * buffer head to be EMPTY, filling the buffer either by file I/O or by
- * USB I/O (during which the buffer head is BUSY), and marking the buffer
- * head FULL when the I/O is complete.  Then the buffer will be emptied
- * (again possibly by USB I/O, during which it is marked BUSY) and
- * finally marked EMPTY again (possibly by a completion routine).
- *
- * A module parameter tells the driver to avoid stalling the bulk
- * endpoints wherever the transport specification allows.  This is
- * necessary for some UDCs like the SuperH, which cannot reliably clear a
- * halt on a bulk endpoint.  However, under certain circumstances the
+/* /\* */
+/*  * file_storage.c -- File-backed USB Storage Gadget, for USB development */
+/*  * */
+/*  * Copyright (C) 2003-2008 Alan Stern */
+/*  * All rights reserved. */
+/*  * */
+/*  * Redistribution and use in source and binary forms, with or without */
+/*  * modification, are permitted provided that the following conditions */
+/*  * are met: */
+/*  * 1. Redistributions of source code must retain the above copyright */
+/*  *    notice, this list of conditions, and the following disclaimer, */
+/*  *    without modification. */
+/*  * 2. Redistributions in binary form must reproduce the above copyright */
+/*  *    notice, this list of conditions and the following disclaimer in the */
+/*  *    documentation and/or other materials provided with the distribution. */
+/*  * 3. The names of the above-listed copyright holders may not be used */
+/*  *    to endorse or promote products derived from this software without */
+/*  *    specific prior written permission. */
+/*  * */
+/*  * ALTERNATIVELY, this software may be distributed under the terms of the */
+/*  * GNU General Public License ("GPL") as published by the Free Software */
+/*  * Foundation, either version 2 of that License or (at your option) any */
+/*  * later version. */
+/*  * */
+/*  * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS */
+/*  * IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, */
+/*  * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR */
+/*  * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR */
+/*  * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, */
+/*  * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, */
+/*  * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR */
+/*  * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF */
+/*  * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING */
+/*  * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS */
+/*  * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */
+/*  *\/ */
+
+
+/* /\* */
+/*  * The File-backed Storage Gadget acts as a USB Mass Storage device, */
+/*  * appearing to the host as a disk drive or as a CD-ROM drive.  In addition */
+/*  * to providing an example of a genuinely useful gadget driver for a USB */
+/*  * device, it also illustrates a technique of double-buffering for increased */
+/*  * throughput.  Last but not least, it gives an easy way to probe the */
+/*  * behavior of the Mass Storage drivers in a USB host. */
+/*  * */
+/*  * Backing storage is provided by a regular file or a block device, specified */
+/*  * by the "file" module parameter.  Access can be limited to read-only by */
+/*  * setting the optional "ro" module parameter.  (For CD-ROM emulation, */
+/*  * access is always read-only.)  The gadget will indicate that it has */
+/*  * removable media if the optional "removable" module parameter is set. */
+/*  * */
+/*  * The gadget supports the Control-Bulk (CB), Control-Bulk-Interrupt (CBI), */
+/*  * and Bulk-Only (also known as Bulk-Bulk-Bulk or BBB) transports, selected */
+/*  * by the optional "transport" module parameter.  It also supports the */
+/*  * following protocols: RBC (0x01), ATAPI or SFF-8020i (0x02), QIC-157 (0c03), */
+/*  * UFI (0x04), SFF-8070i (0x05), and transparent SCSI (0x06), selected by */
+/*  * the optional "protocol" module parameter.  In addition, the default */
+/*  * Vendor ID, Product ID, release number and serial number can be overridden. */
+/*  * */
+/*  * There is support for multiple logical units (LUNs), each of which has */
+/*  * its own backing file.  The number of LUNs can be set using the optional */
+/*  * "luns" module parameter (anywhere from 1 to 8), and the corresponding */
+/*  * files are specified using comma-separated lists for "file" and "ro". */
+/*  * The default number of LUNs is taken from the number of "file" elements; */
+/*  * it is 1 if "file" is not given.  If "removable" is not set then a backing */
+/*  * file must be specified for each LUN.  If it is set, then an unspecified */
+/*  * or empty backing filename means the LUN's medium is not loaded.  Ideally */
+/*  * each LUN would be settable independently as a disk drive or a CD-ROM */
+/*  * drive, but currently all LUNs have to be the same type.  The CD-ROM */
+/*  * emulation includes a single data track and no audio tracks; hence there */
+/*  * need be only one backing file per LUN.  Note also that the CD-ROM block */
+/*  * length is set to 512 rather than the more common value 2048. */
+/*  * */
+/*  * Requirements are modest; only a bulk-in and a bulk-out endpoint are */
+/*  * needed (an interrupt-out endpoint is also needed for CBI).  The memory */
+/*  * requirement amounts to two 16K buffers, size configurable by a parameter. */
+/*  * Support is included for both full-speed and high-speed operation. */
+/*  * */
+/*  * Note that the driver is slightly non-portable in that it assumes a */
+/*  * single memory/DMA buffer will be useable for bulk-in, bulk-out, and */
+/*  * interrupt-in endpoints.  With most device controllers this isn't an */
+/*  * issue, but there may be some with hardware restrictions that prevent */
+/*  * a buffer from being used by more than one endpoint. */
+/*  * */
+/*  * Module options: */
+/*  * */
+/*  *	file=filename[,filename...] */
+/*  *				Required if "removable" is not set, names of */
+/*  *					the files or block devices used for */
+/*  *					backing storage */
+/*  *	ro=b[,b...]		Default false, booleans for read-only access */
+/*  *	removable		Default false, boolean for removable media */
+/*  *	luns=N			Default N = number of filenames, number of */
+/*  *					LUNs to support */
+/*  *	nofua=b[,b...]		Default false, booleans for ignore FUA flag */
+/*  *					in SCSI WRITE(10,12) commands */
+/*  *	stall			Default determined according to the type of */
+/*  *					USB device controller (usually true), */
+/*  *					boolean to permit the driver to halt */
+/*  *					bulk endpoints */
+/*  *	cdrom			Default false, boolean for whether to emulate */
+/*  *					a CD-ROM drive */
+/*  *	transport=XXX		Default BBB, transport name (CB, CBI, or BBB) */
+/*  *	protocol=YYY		Default SCSI, protocol name (RBC, 8020 or */
+/*  *					ATAPI, QIC, UFI, 8070, or SCSI; */
+/*  *					also 1 - 6) */
+/*  *	vendor=0xVVVV		Default 0x0525 (NetChip), USB Vendor ID */
+/*  *	product=0xPPPP		Default 0xa4a5 (FSG), USB Product ID */
+/*  *	release=0xRRRR		Override the USB release number (bcdDevice) */
+/*  *	serial=HHHH...		Override serial number (string of hex chars) */
+/*  *	buflen=N		Default N=16384, buffer size used (will be */
+/*  *					rounded down to a multiple of */
+/*  *					PAGE_CACHE_SIZE) */
+/*  * */
+/*  * If CONFIG_USB_FILE_STORAGE_TEST is not set, only the "file", "ro", */
+/*  * "removable", "luns", "nofua", "stall", and "cdrom" options are available; */
+/*  * default values are used for everything else. */
+/*  * */
+/*  * The pathnames of the backing files and the ro settings are available in */
+/*  * the attribute files "file", "nofua", and "ro" in the lun<n> subdirectory of */
+/*  * the gadget's sysfs directory.  If the "removable" option is set, writing to */
+/*  * these files will simulate ejecting/loading the medium (writing an empty */
+/*  * line means eject) and adjusting a write-enable tab.  Changes to the ro */
+/*  * setting are not allowed when the medium is loaded or if CD-ROM emulation */
+/*  * is being used. */
+/*  * */
+/*  * This gadget driver is heavily based on "Gadget Zero" by David Brownell. */
+/*  * The driver's SCSI command interface was based on the "Information */
+/*  * technology - Small Computer System Interface - 2" document from */
+/*  * X3T9.2 Project 375D, Revision 10L, 7-SEP-93, available at */
+/*  * <http://www.t10.org/ftp/t10/drafts/s2/s2-r10l.pdf>.  The single exception */
+/*  * is opcode 0x23 (READ FORMAT CAPACITIES), which was based on the */
+/*  * "Universal Serial Bus Mass Storage Class UFI Command Specification" */
+/*  * document, Revision 1.0, December 14, 1998, available at */
+/*  * <http://www.usb.org/developers/devclass_docs/usbmass-ufi10.pdf>. */
+/*  *\/ */
+
+
+/* /\* */
+/*  *				Driver Design */
+/*  * */
+/*  * The FSG driver is fairly straightforward.  There is a main kernel */
+/*  * thread that handles most of the work.  Interrupt routines field */
+/*  * callbacks from the controller driver: bulk- and interrupt-request */
+/*  * completion notifications, endpoint-0 events, and disconnect events. */
+/*  * Completion events are passed to the main thread by wakeup calls.  Many */
+/*  * ep0 requests are handled at interrupt time, but SetInterface, */
+/*  * SetConfiguration, and device reset requests are forwarded to the */
+/*  * thread in the form of "exceptions" using SIGUSR1 signals (since they */
+/*  * should interrupt any ongoing file I/O operations). */
+/*  * */
+/*  * The thread's main routine implements the standard command/data/status */
+/*  * parts of a SCSI interaction.  It and its subroutines are full of tests */
+/*  * for pending signals/exceptions -- all this polling is necessary since */
+/*  * the kernel has no setjmp/longjmp equivalents.  (Maybe this is an */
+/*  * indication that the driver really wants to be running in userspace.) */
+/*  * An important point is that so long as the thread is alive it keeps an */
+/*  * open reference to the backing file.  This will prevent unmounting */
+/*  * the backing file's underlying filesystem and could cause problems */
+/*  * during system shutdown, for example.  To prevent such problems, the */
+/*  * thread catches INT, TERM, and KILL signals and converts them into */
+/*  * an EXIT exception. */
+/*  * */
+/*  * In normal operation the main thread is started during the gadget's */
+/*  * fsg_bind() callback and stopped during fsg_unbind().  But it can also */
+/*  * exit when it receives a signal, and there's no point leaving the */
+/*  * gadget running when the thread is dead.  So just before the thread */
+/*  * exits, it deregisters the gadget driver.  This makes things a little */
+/*  * tricky: The driver is deregistered at two places, and the exiting */
+/*  * thread can indirectly call fsg_unbind() which in turn can tell the */
+/*  * thread to exit.  The first problem is resolved through the use of the */
+/*  * REGISTERED atomic bitflag; the driver will only be deregistered once. */
+/*  * The second problem is resolved by having fsg_unbind() check */
+/*  * fsg->state; it won't try to stop the thread if the state is already */
+/*  * FSG_STATE_TERMINATED. */
+/*  * */
+/*  * To provide maximum throughput, the driver uses a circular pipeline of */
+/*  * buffer heads (struct fsg_buffhd).  In principle the pipeline can be */
+/*  * arbitrarily long; in practice the benefits don't justify having more */
+/*  * than 2 stages (i.e., double buffering).  But it helps to think of the */
+/*  * pipeline as being a long one.  Each buffer head contains a bulk-in and */
+/*  * a bulk-out request pointer (since the buffer can be used for both */
+/*  * output and input -- directions always are given from the host's */
+/*  * point of view) as well as a pointer to the buffer and various state */
+/*  * variables. */
+/*  * */
+/*  * Use of the pipeline follows a simple protocol.  There is a variable */
+/*  * (fsg->next_buffhd_to_fill) that points to the next buffer head to use. */
+/*  * At any time that buffer head may still be in use from an earlier */
+/*  * request, so each buffer head has a state variable indicating whether */
+/*  * it is EMPTY, FULL, or BUSY.  Typical use involves waiting for the */
+/*  * buffer head to be EMPTY, filling the buffer either by file I/O or by */
+/*  * USB I/O (during which the buffer head is BUSY), and marking the buffer */
+/*  * head FULL when the I/O is complete.  Then the buffer will be emptied */
+/*  * (again possibly by USB I/O, during which it is marked BUSY) and */
+/*  * finally marked EMPTY again (possibly by a completion routine). */
+/*  * */
+/*  * A module parameter tells the driver to avoid stalling the bulk */
+/*  * endpoints wherever the transport specification allows.  This is */
+/*  * necessary for some UDCs like the SuperH, which cannot reliably clear a */
+/* * halt on a bulk endpoint.  However, under certain circumstances the
  * Bulk-only specification requires a stall.  In such cases the driver
  * will halt the endpoint and set a flag indicating that it should clear
  * the halt in software during the next device reset.  Hopefully this
@@ -299,7 +293,7 @@ static const char fsg_string_interface[] = "Mass Storage";
 #define init_completion(x)
 #define wake_up_process(thread_task) do {} while (0)
 #define send_sig_info(sig,mode,thread_task) do {} while (0)
-#define spinlock_t int
+typedef int spinlock_t;
 #define GFP_ATOMIC ((gfp_t) 0)
 #define GFP_KERNEL ((gfp_t) 0)
 #define set_current_state(...)		do {} while (0)
@@ -322,8 +316,8 @@ static const char fsg_string_interface[] = "Mass Storage";
 #endif
 #define try_to_freeze(...)		0
 #define set_freezable(...)		do { } while (0)
-/* #define kmalloc(x,y)			malloc(x) */
-/* #define kfree(x)			free(x) */
+//#define kmalloc(x,y)			malloc(x)
+//#define kfree(x)			free(x)
 #define kzalloc(size,flags)	calloc(size, 1)
 #define ENOTSUPP	524	/* Operation is not supported */
 #define kthread_create(...)	__builtin_return_address(0)
@@ -351,20 +345,20 @@ static const char fsg_string_interface[] = "Mass Storage";
 struct kref {int x;};
 struct completion {int x;};
 
-inline void set_bit(int nr, void *addr)
+inline void set_bit(int nr, volatile void * addr)
 {
 	int	mask;
-	unsigned int *a = addr;
+	volatile unsigned int *a = addr;
 
 	a += nr >> 5;
 	mask = 1 << (nr & 0x1f);
 	*a |= mask;
 }
 
-inline void clear_bit(int nr, void *addr)
+inline void clear_bit(int nr, volatile void * addr)
 {
 	int	mask;
-	unsigned int *a = addr;
+	volatile unsigned int *a = addr;
 
 	a += nr >> 5;
 	mask = 1 << (nr & 0x1f);
@@ -402,7 +396,7 @@ static struct {
 	int		protocol_type;
 	char		*protocol_name;
 
-} mod_data = {					/* Default values */
+} mod_data = {					// Default values
 	.transport_parm		= "BBB",
 	.protocol_parm		= "SCSI",
 	.removable		= 1,
@@ -410,7 +404,7 @@ static struct {
 	.cdrom			= 0,
 	.vendor			= FSG_VENDOR_ID,
 	.product		= FSG_PRODUCT_ID,
-	.release		= 0xffff,	/* Use controller chip type */
+	.release		= 0xffff,	// Use controller chip type
 	.buflen			= 16384,
 	};
 
@@ -444,17 +438,17 @@ struct fsg_dev {
 	/* reference counting: wait until all LUNs are released */
 	struct kref		ref;
 
-	struct usb_ep		*ep0;		/* Handy copy of gadget->ep0 */
-	struct usb_request	*ep0req;	/* For control responses */
+	struct usb_ep		*ep0;		// Handy copy of gadget->ep0
+	struct usb_request	*ep0req;	// For control responses
 	unsigned int		ep0_req_tag;
 	const char		*ep0req_name;
 
-	struct usb_request	*intreq;	/* For interrupt responses */
+	struct usb_request	*intreq;	// For interrupt responses
 	int			intreq_busy;
 	struct fsg_buffhd	*intr_buffhd;
 
 	unsigned int		bulk_out_maxpacket;
-	enum fsg_state		state;		/* For exception handling */
+	enum fsg_state		state;		// For exception handling
 	unsigned int		exception_req_tag;
 
 	u8			config, new_config;
@@ -588,7 +582,7 @@ config_desc = {
 	.bConfigurationValue =	CONFIG_VALUE,
 	.iConfiguration =	FSG_STRING_CONFIG,
 	.bmAttributes =		USB_CONFIG_ATT_ONE | USB_CONFIG_ATT_SELFPOWER,
-	.bMaxPower =		50, /* ONFIG_USB_GADGET_VBUS_DRAW / 2, */
+	.bMaxPower =		50, //CONFIG_USB_GADGET_VBUS_DRAW / 2,
 };
 
 
@@ -690,6 +684,7 @@ static int ep0_queue(struct fsg_dev *fsg)
 {
 	int	rc;
 
+//printf("%s\n", __func__);
 	rc = usb_ep_queue(fsg->ep0, fsg->ep0req, GFP_ATOMIC);
 	if (rc != 0 && rc != -ESHUTDOWN) {
 
@@ -709,7 +704,7 @@ static void ep0_complete(struct usb_ep *ep, struct usb_request *req)
 	if (req->status || req->actual != req->length)
 		DBG(fsg, "%s --> %d, %u/%u\n", __func__,
 				req->status, req->actual, req->length);
-	if (req->status == -ECONNRESET)		/* Request was cancelled */
+	if (req->status == -ECONNRESET)		// Request was cancelled
 		usb_ep_fifo_flush(ep);
 
 	if (req->status == 0 && req->context)
@@ -730,7 +725,7 @@ static void bulk_in_complete(struct usb_ep *ep, struct usb_request *req)
 	if (req->status || req->actual != req->length)
 		DBG(fsg, "%s --> %d, %u/%u\n", __func__,
 				req->status, req->actual, req->length);
-	if (req->status == -ECONNRESET)		/* Request was cancelled */
+	if (req->status == -ECONNRESET)		// Request was cancelled
 		usb_ep_fifo_flush(ep);
 
 	/* Hold the lock while we update the request and buffer states */
@@ -742,17 +737,25 @@ static void bulk_in_complete(struct usb_ep *ep, struct usb_request *req)
 	spin_unlock(&fsg->lock);
 }
 
+static enum fsg_buffer_state * ga_state;
+static struct fsg_buffhd   *ga_bh;
+static int ga_tag;
+
 static void bulk_out_complete(struct usb_ep *ep, struct usb_request *req)
 {
 	struct fsg_dev		*fsg = ep->driver_data;
 	struct fsg_buffhd	*bh = req->context;
 
+printf("%s %d %x\n",__func__, req->status, req);
+ga_bh = bh;
+ga_tag = fsg->tag;
+
 	dump_msg(fsg, "bulk-out", req->buf, req->actual);
 	if (req->status || req->actual != bh->bulk_out_intended_length)
 		DBG(fsg, "%s --> %d, %u/%u\n", __func__,
 				req->status, req->actual,
 				bh->bulk_out_intended_length);
-	if (req->status == -ECONNRESET)		/* Request was cancelled */
+	if (req->status == -ECONNRESET)		// Request was cancelled
 		usb_ep_fifo_flush(ep);
 
 	/* Hold the lock while we update the request and buffer states */
@@ -762,6 +765,8 @@ static void bulk_out_complete(struct usb_ep *ep, struct usb_request *req)
 	bh->state = BUF_STATE_FULL;
 	wakeup_thread(fsg);
 	spin_unlock(&fsg->lock);
+	//*ga_state = BUF_STATE_FULL;
+printf("%s %d 0x%x\n",__func__, bh->state, (u8 *)bh);
 }
 
 
@@ -805,6 +810,7 @@ static int class_setup_req(struct fsg_dev *fsg,
 			/* Raise an exception to stop the current operation
 			 * and reinitialize our state. */
 			DBG(fsg, "bulk reset request\n");
+printf("bulk reset request\n");
 			raise_exception(fsg, FSG_STATE_RESET);
 			value = DELAYED_STATUS;
 			break;
@@ -818,6 +824,7 @@ static int class_setup_req(struct fsg_dev *fsg,
 				break;
 			}
 			VDBG(fsg, "get max LUN\n");
+printf("get max LUN\n");
 			*(u8 *) req->buf = fsg->nluns - 1;
 			value = 1;
 			break;
@@ -868,17 +875,20 @@ static int standard_setup_req(struct fsg_dev *fsg,
 	u16			w_index = le16_to_cpu(ctrl->wIndex);
 	u16			w_value = le16_to_cpu(ctrl->wValue);
 
+//printf("%s 0x%x\n", __func__, w_value);
 	/* Usually this just stores reply data in the pre-allocated ep0 buffer,
 	 * but config change events will also reconfigure hardware. */
 	switch (ctrl->bRequest) {
-
+	int temp;
 	case USB_REQ_GET_DESCRIPTOR:
 		if (ctrl->bRequestType != (USB_DIR_IN | USB_TYPE_STANDARD |
 				USB_RECIP_DEVICE))
 			break;
-		switch (w_value >> 8) {
+		temp = w_value >> 8;
+		switch (temp/*w_value >> 8*/) {
 
 		case USB_DT_DEVICE:
+//printf("get device descriptor\n");
 			VDBG(fsg, "get device descriptor\n");
 			value = sizeof device_desc;
 			memcpy(req->buf, &device_desc, value);
@@ -897,6 +907,8 @@ static int standard_setup_req(struct fsg_dev *fsg,
 				break;
 			goto get_config;
 		case USB_DT_CONFIG:
+//printf("get config descriptor\n");
+
 			VDBG(fsg, "get configuration descriptor\n");
 get_config:
 			value = populate_config_buf(fsg->gadget,
@@ -968,6 +980,10 @@ get_config:
 		break;
 
 	default:
+	       printf("unknown control req %02x.%02x v%04x i%04x l%u\n",
+                        ctrl->bRequestType, ctrl->bRequest,
+                        w_value, w_index, le16_to_cpu(ctrl->wLength));
+
 		VDBG(fsg,
 			"unknown control req %02x.%02x v%04x i%04x l%u\n",
 			ctrl->bRequestType, ctrl->bRequest,
@@ -985,7 +1001,8 @@ static int fsg_setup(struct usb_gadget *gadget,
 	int			rc;
 	int			w_length = le16_to_cpu(ctrl->wLength);
 
-	++fsg->ep0_req_tag;		/* Record arrival of a new request */
+//printf("%s\n", __func__);
+	++fsg->ep0_req_tag;		// Record arrival of a new request
 	fsg->ep0req->context = NULL;
 	fsg->ep0req->length = 0;
 	dump_msg(fsg, "ep0-setup", (u8 *) ctrl, sizeof(*ctrl));
@@ -1014,7 +1031,6 @@ static int fsg_setup(struct usb_gadget *gadget,
 
 /* All the following routines run in process context */
 
-
 /* Use this for bulk or interrupt transfers, not ep0 */
 static void start_transfer(struct fsg_dev *fsg, struct usb_ep *ep,
 		struct usb_request *req, int *pbusy,
@@ -1030,7 +1046,9 @@ static void start_transfer(struct fsg_dev *fsg, struct usb_ep *ep,
 	spin_lock_irq(&fsg->lock);
 	*pbusy = 1;
 	*state = BUF_STATE_BUSY;
+	//ga_state = state;
 	spin_unlock_irq(&fsg->lock);
+printf("%s\n", __func__);
 	rc = usb_ep_queue(ep, req, GFP_KERNEL);
 	if (rc != 0) {
 		*pbusy = 0;
@@ -1047,10 +1065,8 @@ static void start_transfer(struct fsg_dev *fsg, struct usb_ep *ep,
 	}
 }
 
-static void busy_indicator(void)
-{
-	static int state;
-
+static void busy_indicator(void) {
+	static int state = 0;
 	switch (state) {
 	case 0:
 		puts("\r|");break;
@@ -1068,8 +1084,6 @@ static void busy_indicator(void)
 		puts("\r-");break;
 	case 7:
 		puts("\r\\");break;
-	default:
-		state = 0;
 	}
 	if (state++ == 8)
 		state = 0;
@@ -1143,7 +1157,7 @@ static int do_read(struct fsg_dev *fsg)
 	/* Carry out the file reads */
 	amount_left = fsg->data_size_from_cmnd;
 	if (unlikely(amount_left == 0))
-		return -EIO;		/* No default reply */
+		return -EIO;		// No default reply
 
 	for (;;) {
 
@@ -1171,6 +1185,9 @@ static int do_read(struct fsg_dev *fsg)
 				return rc;
 		}
 
+printf("do_read %s %x\n", __func__, (u8 *)bh->buf);
+bh->inreq->buf = bh->buf;
+
 		/* If we were asked to read past the end of file,
 		 * end with an empty buffer. */
 		if (amount == 0) {
@@ -1189,15 +1206,14 @@ static int do_read(struct fsg_dev *fsg)
 		nread = 0;
 		while (amount_tmp > 0) {
 			ums_info->read_sector(&(ums_info->ums_dev),
-					      (file_offset_tmp + nread)
-					      / SECTOR_SIZE,
+			                      (file_offset_tmp + nread) / SECTOR_SIZE,
 					      (char __user *)bh->buf + nread);
 			amount_tmp -= SECTOR_SIZE;
 			nread += SECTOR_SIZE;
 		}
 		file_offset_tmp += amount;
 
-		VLDBG(curlun, "file read %u @ %llu -> %d\n", amount,
+		VLDBG(curlun, "file read %u  <at>  %llu -> %d\n", amount,
 				(unsigned long long) file_offset,
 				(int) nread);
 		if (signal_pending(current))
@@ -1210,7 +1226,7 @@ static int do_read(struct fsg_dev *fsg)
 		} else if (nread < amount) {
 			LDBG(curlun, "partial file read: %d/%u\n",
 					(int) nread, amount);
-			nread -= (nread & 511);	/* Round down to a block */
+			nread -= (nread & 511);	// Round down to a block
 		}
 		file_offset  += nread;
 		amount_left  -= nread;
@@ -1227,16 +1243,17 @@ static int do_read(struct fsg_dev *fsg)
 		}
 
 		if (amount_left == 0)
-			break;		/* No more left to read */
+			break;		// No more left to read
 
 		/* Send this buffer and go read some more */
 		bh->inreq->zero = 0;
+printf("do_read %x\n", (u8 *)bh);
 		start_transfer(fsg, fsg->bulk_in, bh->inreq,
 				&bh->inreq_busy, &bh->state);
 		fsg->next_buffhd_to_fill = bh->next;
 	}
 
-	return -EIO;		/* No default reply */
+	return -EIO;		// No default reply
 }
 
 
@@ -1338,6 +1355,7 @@ static int do_write(struct fsg_dev *fsg)
 			bh->outreq->length = bh->bulk_out_intended_length =
 					amount;
 			bh->outreq->short_not_ok = 1;
+printf("%s %x\n", __func__, (u8 *)bh);
 			start_transfer(fsg, fsg->bulk_out, bh->outreq,
 					&bh->outreq_busy, &bh->state);
 			fsg->next_buffhd_to_fill = bh->next;
@@ -1347,7 +1365,7 @@ static int do_write(struct fsg_dev *fsg)
 		/* Write the received data to the backing file */
 		bh = fsg->next_buffhd_to_drain;
 		if (bh->state == BUF_STATE_EMPTY && !get_some_more)
-			break;			/* We stopped early */
+			break;			// We stopped early
 		if (bh->state == BUF_STATE_FULL) {
 			smp_rmb();
 			fsg->next_buffhd_to_drain = bh->next;
@@ -1364,7 +1382,7 @@ static int do_write(struct fsg_dev *fsg)
 			amount = bh->outreq->actual;
 			if (curlun->file_length - file_offset < amount) {
 				LERROR(curlun,
-	"write %u @ %llu beyond end %llu\n",
+	"write %u  <at>  %llu beyond end %llu\n",
 	amount, (unsigned long long) file_offset,
 	(unsigned long long) curlun->file_length);
 				amount = curlun->file_length - file_offset;
@@ -1375,22 +1393,18 @@ static int do_write(struct fsg_dev *fsg)
 			amount_tmp = amount;
 			nwritten = 0;
 			while (amount_tmp > 0) {
-				ums_info->write_sector(&(ums_info->ums_dev),
-						       (file_offset_tmp
-							+ nwritten)
-						       / SECTOR_SIZE,
-						       (char __user *)bh->buf
-						       + nwritten);
+				ums_info->write_sector(&(ums_info->ums_dev), (file_offset_tmp + nwritten) / SECTOR_SIZE,
+						       (char __user *)bh->buf + nwritten);
 				amount_tmp -= SECTOR_SIZE;
 				nwritten += SECTOR_SIZE;
 			}
 			file_offset_tmp += amount;
 
-			VLDBG(curlun, "file write %u @ %llu -> %d\n", amount,
+			VLDBG(curlun, "file write %u  <at>  %llu -> %d\n", amount,
 					(unsigned long long) file_offset,
 					(int) nwritten);
 			if (signal_pending(current))
-				return -EINTR;		/* Interrupted! */
+				return -EINTR;		// Interrupted!
 
 			if (nwritten < 0) {
 				LDBG(curlun, "error in file write: %d\n",
@@ -1400,7 +1414,7 @@ static int do_write(struct fsg_dev *fsg)
 				LDBG(curlun, "partial file write: %d/%u\n",
 						(int) nwritten, amount);
 				nwritten -= (nwritten & 511);
-						/* Round down to a block */
+						// Round down to a block
 			}
 			file_offset += nwritten;
 			amount_left_to_write -= nwritten;
@@ -1428,7 +1442,7 @@ static int do_write(struct fsg_dev *fsg)
 			return rc;
 	}
 
-	return -EIO;		/* No default reply */
+	return -EIO;		// No default reply
 }
 
 
@@ -1478,7 +1492,7 @@ static int do_verify(struct fsg_dev *fsg)
 
 	verification_length = get_unaligned_be16(&fsg->cmnd[7]);
 	if (unlikely(verification_length == 0))
-		return -EIO;		/* No default reply */
+		return -EIO;		// No default reply
 
 	/* Prepare to carry out the file verify */
 	amount_left = verification_length << 9;
@@ -1517,16 +1531,14 @@ static int do_verify(struct fsg_dev *fsg)
 		amount_tmp = amount;
 		nread = 0;
 		while (amount_tmp > 0) {
-			ums_info->read_sector(&(ums_info->ums_dev),
-					      (file_offset_tmp + nread)
-					      / SECTOR_SIZE,
+			ums_info->read_sector(&(ums_info->ums_dev), (file_offset_tmp + nread) / SECTOR_SIZE,
 					      (char __user *)bh->buf + nread);
 			amount_tmp -= SECTOR_SIZE;
 			nread += SECTOR_SIZE;
 		}
 		file_offset_tmp += amount;
 
-		VLDBG(curlun, "file read %u @ %llu -> %d\n", amount,
+		VLDBG(curlun, "file read %u  <at>  %llu -> %d\n", amount,
 				(unsigned long long) file_offset,
 				(int) nread);
 		if (signal_pending(current))
@@ -1539,7 +1551,7 @@ static int do_verify(struct fsg_dev *fsg)
 		} else if (nread < amount) {
 			LDBG(curlun, "partial file verify: %d/%u\n",
 					(int) nread, amount);
-			nread -= (nread & 511);	/* Round down to a sector */
+			nread -= (nread & 511);	// Round down to a sector
 		}
 		if (nread == 0) {
 			curlun->sense_data = SS_UNRECOVERED_READ_ERROR;
@@ -1560,29 +1572,33 @@ static int do_inquiry(struct fsg_dev *fsg, struct fsg_buffhd *bh)
 {
 	u8	*buf = (u8 *) bh->buf;
 
-	static const char vendor_id[] = "Linux   ";
-	static const char product_cdrom_id[] = "File-CD Gadget  ";
+	static char vendor_id[] = "Linux   ";
+	static char product_cdrom_id[] = "File-CD Gadget  ";
+
+printf("B %s %x\n", __func__, (u8 *)bh->buf);
+bh->inreq->buf = bh->buf;	
 
-	if (!fsg->curlun) {		/* Unsupported LUNs are okay */
+	if (!fsg->curlun) {		// Unsupported LUNs are okay
 		fsg->bad_lun_okay = 1;
 		memset(buf, 0, 36);
-		buf[0] = 0x7f;		/* Unsupported, no device-type */
-		buf[4] = 31;		/* Additional length */
+		buf[0] = 0x7f;		// Unsupported, no device-type
+		buf[4] = 31;		// Additional length
 		return 36;
 	}
 
+printf("A %s\n", __func__);
 	memset(buf, 0, 8);
 	buf[0] = (mod_data.cdrom ? TYPE_CDROM : TYPE_DISK);
 	if (mod_data.removable)
 		buf[1] = 0x80;
-	buf[2] = 2;		/* ANSI SCSI level 2 */
-	buf[3] = 2;		/* SCSI-2 INQUIRY data format */
-	buf[4] = 31;		/* Additional length */
-				/* No special options */
-	sprintf((char *) (buf + 8), "%-8s%-16s%04x", (char *) vendor_id,
+	buf[2] = 2;		// ANSI SCSI level 2
+	buf[3] = 2;		// SCSI-2 INQUIRY data format
+	buf[4] = 31;		// Additional length
+				// No special options
+	sprintf(buf + 8, "%-8s%-16s%04x", vendor_id,
 			(mod_data.cdrom ? product_cdrom_id :
 				ums_info->name),
-		(u16) mod_data.release);
+		(char *)mod_data.release);
 	return 36;
 }
 
@@ -1616,7 +1632,10 @@ static int do_request_sense(struct fsg_dev *fsg, struct fsg_buffhd *bh)
 	}
 #endif
 
-	if (!curlun) {		/* Unsupported LUNs are okay */
+printf("C %s %x\n", __func__, (u8 *)bh->buf);
+bh->inreq->buf = bh->buf;
+
+	if (!curlun) {		// Unsupported LUNs are okay
 		fsg->bad_lun_okay = 1;
 		sd = SS_LOGICAL_UNIT_NOT_SUPPORTED;
 		sdinfo = 0;
@@ -1631,10 +1650,10 @@ static int do_request_sense(struct fsg_dev *fsg, struct fsg_buffhd *bh)
 	}
 
 	memset(buf, 0, 18);
-	buf[0] = valid | 0x70;			/* Valid, current error */
+	buf[0] = valid | 0x70;			// Valid, current error
 	buf[2] = SK(sd);
 	put_unaligned_be32(sdinfo, &buf[3]);	/* Sense information */
-	buf[7] = 18 - 8;			/* Additional sense length */
+	buf[7] = 18 - 8;			// Additional sense length
 	buf[12] = ASC(sd);
 	buf[13] = ASCQ(sd);
 	return 18;
@@ -1648,12 +1667,15 @@ static int do_read_capacity(struct fsg_dev *fsg, struct fsg_buffhd *bh)
 	int		pmi = fsg->cmnd[8];
 	u8		*buf = (u8 *) bh->buf;
 
+printf("C %s %x ", __func__, (u8 *)bh->buf);
+bh->inreq->buf = bh->buf;
 	/* Check the PMI and LBA fields */
 	if (pmi > 1 || (pmi == 0 && lba != 0)) {
 		curlun->sense_data = SS_INVALID_FIELD_IN_CDB;
 		return -EINVAL;
 	}
 
+printf("read cap\n");
 	put_unaligned_be32(curlun->num_sectors - 1, &buf[0]);
 						/* Max logical block */
 	put_unaligned_be32(512, &buf[4]);	/* Block length */
@@ -1723,7 +1745,7 @@ static int do_mode_sense(struct fsg_dev *fsg, struct fsg_buffhd *bh)
 	int		valid_page = 0;
 	int		len, limit;
 
-	if ((fsg->cmnd[1] & ~0x08) != 0) {		/* Mask away DBD */
+	if ((fsg->cmnd[1] & ~0x08) != 0) {		// Mask away DBD
 		curlun->sense_data = SS_INVALID_FIELD_IN_CDB;
 		return -EINVAL;
 	}
@@ -1733,6 +1755,9 @@ static int do_mode_sense(struct fsg_dev *fsg, struct fsg_buffhd *bh)
 		curlun->sense_data = SS_SAVING_PARAMETERS_NOT_SUPPORTED;
 		return -EINVAL;
 	}
+printf("C %s %x ", __func__, (u8 *)bh->buf);
+bh->inreq->buf = bh->buf;
+
 	changeable_values = (pc == 1);
 	all_pages = (page_code == 0x3f);
 
@@ -1742,13 +1767,13 @@ static int do_mode_sense(struct fsg_dev *fsg, struct fsg_buffhd *bh)
 	 * the mode data length later. */
 	memset(buf, 0, 8);
 	if (mscmnd == SC_MODE_SENSE_6) {
-		buf[2] = (curlun->ro ? 0x80 : 0x00);		/* WP, DPOFUA */
+		buf[2] = (curlun->ro ? 0x80 : 0x00);		// WP, DPOFUA
 		buf += 4;
 		limit = 255;
-	} else {			/* SC_MODE_SENSE_10 */
-		buf[3] = (curlun->ro ? 0x80 : 0x00);		/* WP, DPOFUA */
+	} else {			// SC_MODE_SENSE_10
+		buf[3] = (curlun->ro ? 0x80 : 0x00);		// WP, DPOFUA
 		buf += 8;
-		limit = 65535;		/* Should really be mod_data.buflen */
+		limit = 65535;		// Should really be mod_data.buflen
 	}
 
 	/* No block descriptors */
@@ -1757,14 +1782,14 @@ static int do_mode_sense(struct fsg_dev *fsg, struct fsg_buffhd *bh)
 	 * is the Caching page. */
 	if (page_code == 0x08 || all_pages) {
 		valid_page = 1;
-		buf[0] = 0x08;		/* Page code */
-		buf[1] = 10;		/* Page length */
-		memset(buf+2, 0, 10);	/* None of the fields are changeable */
+		buf[0] = 0x08;		// Page code
+		buf[1] = 10;		// Page length
+		memset(buf+2, 0, 10);	// None of the fields are changeable
 
 		if (!changeable_values) {
-			buf[2] = 0x04;	/* Write cache enable, */
-					/* Read cache not disabled */
-					/* No cache retention priorities */
+			buf[2] = 0x04;	// Write cache enable,
+					// Read cache not disabled
+					// No cache retention priorities
 			put_unaligned_be16(0xffff, &buf[4]);
 					/* Don't disable prefetch */
 					/* Minimum prefetch = 0 */
@@ -1803,7 +1828,7 @@ static int do_start_stop(struct fsg_dev *fsg)
 		return -EINVAL;
 	}
 
-	/* int immed = fsg->cmnd[1] & 0x01; */
+	// int immed = fsg->cmnd[1] & 0x01;
 	loej = fsg->cmnd[4] & 0x02;
 	start = fsg->cmnd[4] & 0x01;
 
@@ -1822,7 +1847,7 @@ static int do_prevent_allow(struct fsg_dev *fsg)
 	}
 
 	prevent = fsg->cmnd[4] & 0x01;
-	if ((fsg->cmnd[4] & ~0x01) != 0) {		/* Mask away Prevent */
+	if ((fsg->cmnd[4] & ~0x01) != 0) {		// Mask away Prevent
 		curlun->sense_data = SS_INVALID_FIELD_IN_CDB;
 		return -EINVAL;
 	}
@@ -1840,8 +1865,10 @@ static int do_read_format_capacities(struct fsg_dev *fsg,
 	struct fsg_lun	*curlun = fsg->curlun;
 	u8		*buf = (u8 *) bh->buf;
 
+printf("%s\n",__func__);
+bh->inreq->buf = bh->buf;
 	buf[0] = buf[1] = buf[2] = 0;
-	buf[3] = 8;	/* Only the Current/Maximum Capacity Descriptor */
+	buf[3] = 8;		// Only the Current/Maximum Capacity Descriptor
 	buf += 4;
 
 	put_unaligned_be32(curlun->num_sectors, &buf[0]);
@@ -1891,7 +1918,7 @@ static int wedge_bulk_in_endpoint(struct fsg_dev *fsg)
 	int	rc;
 
 	DBG(fsg, "bulk-in set wedge\n");
-	rc = 0; /* sb_ep_set_wedge(fsg->bulk_in); */
+	rc = 0; //usb_ep_set_wedge(fsg->bulk_in);
 	if (rc == -EAGAIN)
 		VDBG(fsg, "delayed bulk-in endpoint wedge\n");
 	while (rc != 0) {
@@ -1904,7 +1931,7 @@ static int wedge_bulk_in_endpoint(struct fsg_dev *fsg)
 		/* Wait for a short time and then try again */
 		if (msleep_interruptible(100) != 0)
 			return -EINTR;
-		/* c = usb_ep_set_wedge(fsg->bulk_in); */
+		//rc = usb_ep_set_wedge(fsg->bulk_in);
 	}
 	return rc;
 }
@@ -1916,7 +1943,7 @@ static int pad_with_zeros(struct fsg_dev *fsg)
 	u32			nsend;
 	int			rc;
 
-	bh->state = BUF_STATE_EMPTY;		/* For the first iteration */
+	bh->state = BUF_STATE_EMPTY;		// For the first iteration
 	fsg->usb_amount_left = nkeep + fsg->residue;
 	while (fsg->usb_amount_left > 0) {
 
@@ -1929,8 +1956,9 @@ static int pad_with_zeros(struct fsg_dev *fsg)
 
 		nsend = min(fsg->usb_amount_left, (u32) mod_data.buflen);
 		memset(bh->buf + nkeep, 0, nsend - nkeep);
-		bh->inreq->length = nsend;
+		//bh->inreq->length = nsend;
 		bh->inreq->zero = 0;
+printf("%s %x %d %d\n", __func__, (u8 *)bh, bh->inreq->length, nsend);
 		start_transfer(fsg, fsg->bulk_in, bh->inreq,
 				&bh->inreq_busy, &bh->state);
 		bh = fsg->next_buffhd_to_fill = bh->next;
@@ -1975,6 +2003,7 @@ static int throw_away_data(struct fsg_dev *fsg)
 			bh->outreq->length = bh->bulk_out_intended_length =
 					amount;
 			bh->outreq->short_not_ok = 1;
+printf("%s %x\n", __func__, (u8 *)bh);
 			start_transfer(fsg, fsg->bulk_out, bh->outreq,
 					&bh->outreq_busy, &bh->state);
 			fsg->next_buffhd_to_fill = bh->next;
@@ -1998,7 +2027,7 @@ static int finish_reply(struct fsg_dev *fsg)
 
 	switch (fsg->data_dir) {
 	case DATA_DIR_NONE:
-		break;			/* Nothing to send */
+		break;			// Nothing to send
 
 	/* If we don't know whether the host wants to read or write,
 	 * this must be CB or CBI with an unknown command.  We mustn't
@@ -2013,8 +2042,10 @@ static int finish_reply(struct fsg_dev *fsg)
 
 	/* All but the last buffer of data must have already been sent */
 	case DATA_DIR_TO_HOST:
-		if (fsg->data_size == 0)
-			; /* Nothing to send */
+printf("residue 0x%x %x", fsg->residue, (u8 *)bh);
+		if (fsg->data_size == 0){
+			;		// Nothing to send
+		}
 		/* If there's no residue, simply send the last buffer */
 		else if (fsg->residue == 0) {
 			bh->inreq->zero = 0;
@@ -2037,6 +2068,7 @@ static int finish_reply(struct fsg_dev *fsg)
 				rc = halt_bulk_in_endpoint(fsg);
 			} else {
 				bh->inreq->zero = 1;
+printf("bbb %s %x\n", __func__, (u8 *)bh);
 				start_transfer(fsg, fsg->bulk_in, bh->inreq,
 						&bh->inreq_busy, &bh->state);
 				fsg->next_buffhd_to_fill = bh->next;
@@ -2049,6 +2081,7 @@ static int finish_reply(struct fsg_dev *fsg)
 		else {
 			if (mod_data.can_stall) {
 				bh->inreq->zero = 1;
+printf("stall %s %x\n", __func__, (u8 *)bh);
 				start_transfer(fsg, fsg->bulk_in, bh->inreq,
 						&bh->inreq_busy, &bh->state);
 				fsg->next_buffhd_to_fill = bh->next;
@@ -2062,7 +2095,7 @@ static int finish_reply(struct fsg_dev *fsg)
 	 * There may still be outstanding bulk-out requests. */
 	case DATA_DIR_FROM_HOST:
 		if (fsg->residue == 0)
-			;		/* Nothing to receive */
+			;		// Nothing to receive
 
 		/* Did the host stop sending unexpectedly early? */
 		else if (fsg->short_packet_received) {
@@ -2104,7 +2137,13 @@ static int send_status(struct fsg_dev *fsg)
 
 	/* Wait for the next buffer to become available */
 	bh = fsg->next_buffhd_to_fill;
+printf("%s %x %d\n", __func__,  (u8 *)bh, bh->state);
 	while (bh->state != BUF_STATE_EMPTY) {
+if (bh->state == BUF_STATE_FULL)
+{
+	bh->state = BUF_STATE_EMPTY;
+	break;
+}
 		rc = sleep_thread(fsg, __LINE__);
 		if (rc)
 			return rc;
@@ -2141,15 +2180,18 @@ static int send_status(struct fsg_dev *fsg)
 
 		bh->inreq->length = USB_BULK_CS_WRAP_LEN;
 		bh->inreq->zero = 0;
+bh->inreq->buf = bh->buf;
+printf("bbb %s %x %d\n", __func__, (u8 *)bh, bh->state);
 		start_transfer(fsg, fsg->bulk_in, bh->inreq,
 				&bh->inreq_busy, &bh->state);
 
+
 	} else if (mod_data.transport_type == USB_PR_CB) {
 
 		/* Control-Bulk transport has no status phase! */
 		return 0;
 
-	} else {			/* USB_PR_CBI */
+	} else {			// USB_PR_CBI
 		struct interrupt_data	*buf = bh->buf;
 
 		/* Store and send the Interrupt data.  UFI sends the ASC
@@ -2164,9 +2206,10 @@ static int send_status(struct fsg_dev *fsg)
 		}
 		fsg->intreq->length = CBI_INTERRUPT_DATA_LEN;
 
-		fsg->intr_buffhd = bh;		/* Point to the right buffhd */
+		fsg->intr_buffhd = bh;		// Point to the right buffhd
 		fsg->intreq->buf = bh->inreq->buf;
 		fsg->intreq->context = bh;
+printf("else %s %x\n", __func__, (u8 *)bh);
 		start_transfer(fsg, fsg->intr_in, fsg->intreq,
 				&fsg->intreq_busy, &bh->state);
 	}
@@ -2179,7 +2222,7 @@ static int send_status(struct fsg_dev *fsg)
 /*-------------------------------------------------------------------------*/
 
 /* Check whether the command is properly formed and whether its data size
- * and direction agree with the values we already have. */
++ * and direction agree with the values we already have. */
 static int check_command(struct fsg_dev *fsg, int cmnd_size,
 		enum data_direction data_dir, unsigned int mask,
 		int needs_medium, const char *name)
@@ -2209,7 +2252,7 @@ static int check_command(struct fsg_dev *fsg, int cmnd_size,
 	if (fsg->data_dir != DATA_DIR_UNKNOWN)
 		sprintf(hdlen, ", H%c=%u", dirletter[(int) fsg->data_dir],
 				fsg->data_size);
-	VDBG(fsg, "SCSI command: %s;  Dc=%d, D%c=%u;  Hc=%d%s\n",
+	printf("SCSI command: %s;  Dc=%d, D%c=%u;  Hc=%d%s\n",
 			name, cmnd_size, dirletter[(int) data_dir],
 			fsg->data_size_from_cmnd, fsg->cmnd_size, hdlen);
 
@@ -2217,11 +2260,11 @@ static int check_command(struct fsg_dev *fsg, int cmnd_size,
 	 * and size. */
 	if (fsg->data_size_from_cmnd == 0)
 		data_dir = DATA_DIR_NONE;
-	if (fsg->data_dir == DATA_DIR_UNKNOWN) {	/* CB or CBI */
+	if (fsg->data_dir == DATA_DIR_UNKNOWN) {	// CB or CBI
 		fsg->data_dir = data_dir;
 		fsg->data_size = fsg->data_size_from_cmnd;
 
-	} else {					/* Bulk-only */
+	} else {					// Bulk-only
 		if (fsg->data_size < fsg->data_size_from_cmnd) {
 
 			/* Host data size < Device data size is a phase error.
@@ -2236,6 +2279,7 @@ static int check_command(struct fsg_dev *fsg, int cmnd_size,
 	/* Conflicting data directions is a phase error */
 	if (fsg->data_dir != data_dir && fsg->data_size_from_cmnd > 0) {
 		fsg->phase_error = 1;
+printf("phase error\n");
 		return -EINVAL;
 	}
 
@@ -2255,12 +2299,14 @@ static int check_command(struct fsg_dev *fsg, int cmnd_size,
 		 * be 6 as well.
 		 */
 		if (cmnd_size <= fsg->cmnd_size) {
-			DBG(fsg, "%s is buggy! Expected length %d "
+			printf("%s is buggy! Expected length %d "
 					"but we got %d\n", name,
 					cmnd_size, fsg->cmnd_size);
 			cmnd_size = fsg->cmnd_size;
 		} else {
 			fsg->phase_error = 1;
+printf("length error\n");
+
 			return -EINVAL;
 		}
 	}
@@ -2268,11 +2314,11 @@ static int check_command(struct fsg_dev *fsg, int cmnd_size,
 	/* Check that the LUN values are consistent */
 	if (transport_is_bbb()) {
 		if (fsg->lun != lun)
-			DBG(fsg, "using LUN %d from CBW, "
+			printf("using LUN %d from CBW, "
 					"not LUN %d from CDB\n",
 					fsg->lun, lun);
 	} else
-		fsg->lun = lun;		/* Use LUN from the command */
+		fsg->lun = lun;		// Use LUN from the command
 
 	/* Check the LUN */
 	if (fsg->lun >= 0 && fsg->lun < fsg->nluns) {
@@ -2290,7 +2336,7 @@ static int check_command(struct fsg_dev *fsg, int cmnd_size,
 		 * to use unsupported LUNs; all others may not. */
 		if (fsg->cmnd[0] != SC_INQUIRY &&
 				fsg->cmnd[0] != SC_REQUEST_SENSE) {
-			DBG(fsg, "unsupported LUN %d\n", fsg->lun);
+			printf( "unsupported LUN %d\n", fsg->lun);
 			return -EINVAL;
 		}
 	}
@@ -2299,19 +2345,30 @@ static int check_command(struct fsg_dev *fsg, int cmnd_size,
 	 * REQUEST SENSE commands are allowed; anything else must fail. */
 	if (curlun && curlun->unit_attention_data != SS_NO_SENSE &&
 			fsg->cmnd[0] != SC_INQUIRY &&
-			fsg->cmnd[0] != SC_REQUEST_SENSE) {
+			fsg->cmnd[0] != SC_REQUEST_SENSE &&
+			fsg->cmnd[0] != SC_READ_FORMAT_CAPACITIES &&
+			fsg->cmnd[0] != SC_READ_CAPACITY && 
+			fsg->cmnd[0] != SC_READ_10 &&
+			fsg->cmnd[0] != SC_MODE_SENSE_6
+		) {
 		curlun->sense_data = curlun->unit_attention_data;
 		curlun->unit_attention_data = SS_NO_SENSE;
+printf("attention error\n");
 		return -EINVAL;
 	}
 
 	/* Check that only command bytes listed in the mask are non-zero */
-	fsg->cmnd[1] &= 0x1f;			/* Mask away the LUN */
+	fsg->cmnd[1] &= 0x1f;			// Mask away the LUN
 	for (i = 1; i < cmnd_size; ++i) {
 		if (fsg->cmnd[i] && !(mask & (1 << i))) {
+
+#if 1  //Victor added
 			if (curlun)
 				curlun->sense_data = SS_INVALID_FIELD_IN_CDB;
-			return -EINVAL;
+printf("mask error\n");
+			//return -EINVAL;
+#endif
+
 		}
 	}
 
@@ -2339,99 +2396,91 @@ static int do_scsi_command(struct fsg_dev *fsg)
 	fsg->phase_error = 0;
 	fsg->short_packet_received = 0;
 
-	down_read(&fsg->filesem);	/* We're using the backing file */
+printf("fsg_cmnd 0x%x\n", fsg->cmnd[0]);
+	down_read(&fsg->filesem);	// We're using the backing file
 	switch (fsg->cmnd[0]) {
 
 	case SC_INQUIRY:
+//printf("SC_INQUIRY %x\n", (u8 *)bh);
 		fsg->data_size_from_cmnd = fsg->cmnd[4];
-		reply = check_command(fsg, 6, DATA_DIR_TO_HOST,
-				      (1<<4), 0,
-				      "INQUIRY");
-		if (reply == 0)
+		if ((reply = check_command(fsg, 6, DATA_DIR_TO_HOST,
+				(1<<4), 0,
+				"INQUIRY")) == 0)
 			reply = do_inquiry(fsg, bh);
 		break;
 
 	case SC_MODE_SELECT_6:
 		fsg->data_size_from_cmnd = fsg->cmnd[4];
-		reply = check_command(fsg, 6, DATA_DIR_FROM_HOST,
-				      (1<<1) | (1<<4), 0,
-				      "MODE SELECT(6)");
-		if (reply == 0)
+		if ((reply = check_command(fsg, 6, DATA_DIR_FROM_HOST,
+				(1<<1) | (1<<4), 0,
+				"MODE SELECT(6)")) == 0)
 			reply = do_mode_select(fsg, bh);
 		break;
 
 	case SC_MODE_SELECT_10:
 		fsg->data_size_from_cmnd = get_unaligned_be16(&fsg->cmnd[7]);
-		reply = check_command(fsg, 10, DATA_DIR_FROM_HOST,
-				      (1<<1) | (3<<7), 0,
-				      "MODE SELECT(10)");
-		if (reply == 0)
+		if ((reply = check_command(fsg, 10, DATA_DIR_FROM_HOST,
+				(1<<1) | (3<<7), 0,
+				"MODE SELECT(10)")) == 0)
 			reply = do_mode_select(fsg, bh);
 		break;
 
 	case SC_MODE_SENSE_6:
 		fsg->data_size_from_cmnd = fsg->cmnd[4];
-		reply = check_command(fsg, 6, DATA_DIR_TO_HOST,
-				      (1<<1) | (1<<2) | (1<<4), 0,
-				      "MODE SENSE(6)");
-		if (reply == 0)
+		if ((reply = check_command(fsg, 6, DATA_DIR_TO_HOST,
+				(1<<1) | (1<<2) | (1<<4), 0,
+				"MODE SENSE(6)")) == 0)
 			reply = do_mode_sense(fsg, bh);
 		break;
 
 	case SC_MODE_SENSE_10:
 		fsg->data_size_from_cmnd = get_unaligned_be16(&fsg->cmnd[7]);
-		reply = check_command(fsg, 10, DATA_DIR_TO_HOST,
-				      (1<<1) | (1<<2) | (3<<7), 0,
-				      "MODE SENSE(10)");
-		if (reply == 0)
+		if ((reply = check_command(fsg, 10, DATA_DIR_TO_HOST,
+				(1<<1) | (1<<2) | (3<<7), 0,
+				"MODE SENSE(10)")) == 0)
 			reply = do_mode_sense(fsg, bh);
 		break;
 
 	case SC_PREVENT_ALLOW_MEDIUM_REMOVAL:
 		fsg->data_size_from_cmnd = 0;
-		reply = check_command(fsg, 6, DATA_DIR_NONE,
-				      (1<<4), 0,
-				      "PREVENT-ALLOW MEDIUM REMOVAL");
-		if (reply == 0)
+		if ((reply = check_command(fsg, 6, DATA_DIR_NONE,
+				(1<<4), 0,
+				"PREVENT-ALLOW MEDIUM REMOVAL")) == 0)
 			reply = do_prevent_allow(fsg);
 		break;
 
 	case SC_READ_6:
 		i = fsg->cmnd[4];
 		fsg->data_size_from_cmnd = (i == 0 ? 256 : i) << 9;
-		reply = check_command(fsg, 6, DATA_DIR_TO_HOST,
-				      (7<<1) | (1<<4), 1,
-				      "READ(6)");
-		if (reply == 0)
+		if ((reply = check_command(fsg, 6, DATA_DIR_TO_HOST,
+				(7<<1) | (1<<4), 1,
+				"READ(6)")) == 0)
 			reply = do_read(fsg);
 		break;
 
 	case SC_READ_10:
 		fsg->data_size_from_cmnd =
 				get_unaligned_be16(&fsg->cmnd[7]) << 9;
-		reply = check_command(fsg, 10, DATA_DIR_TO_HOST,
-				      (1<<1) | (0xf<<2) | (3<<7), 1,
-				      "READ(10)");
-		if (reply == 0)
+		if ((reply = check_command(fsg, 10, DATA_DIR_TO_HOST,
+				(1<<1) | (0xf<<2) | (3<<7), 1,
+				"READ(10)")) == 0)
 			reply = do_read(fsg);
 		break;
 
 	case SC_READ_12:
 		fsg->data_size_from_cmnd =
 				get_unaligned_be32(&fsg->cmnd[6]) << 9;
-		reply = check_command(fsg, 12, DATA_DIR_TO_HOST,
-				      (1<<1) | (0xf<<2) | (0xf<<6), 1,
-				      "READ(12)");
-		if (reply == 0)
+		if ((reply = check_command(fsg, 12, DATA_DIR_TO_HOST,
+				(1<<1) | (0xf<<2) | (0xf<<6), 1,
+				"READ(12)")) == 0)
 			reply = do_read(fsg);
 		break;
 
 	case SC_READ_CAPACITY:
 		fsg->data_size_from_cmnd = 8;
-		reply = check_command(fsg, 10, DATA_DIR_TO_HOST,
-				      (0xf<<2) | (1<<8), 1,
-				      "READ CAPACITY");
-		if (reply == 0)
+		if ((reply = check_command(fsg, 10, DATA_DIR_TO_HOST,
+				(0xf<<2) | (1<<8), 1,
+				"READ CAPACITY")) == 0)
 			reply = do_read_capacity(fsg, bh);
 		break;
 
@@ -2439,10 +2488,9 @@ static int do_scsi_command(struct fsg_dev *fsg)
 		if (!mod_data.cdrom)
 			goto unknown_cmnd;
 		fsg->data_size_from_cmnd = get_unaligned_be16(&fsg->cmnd[7]);
-		reply = check_command(fsg, 10, DATA_DIR_TO_HOST,
-				      (3<<7) | (0x1f<<1), 1,
-				      "READ HEADER");
-		if (reply == 0)
+		if ((reply = check_command(fsg, 10, DATA_DIR_TO_HOST,
+				(3<<7) | (0x1f<<1), 1,
+				"READ HEADER")) == 0)
 			reply = do_read_header(fsg, bh);
 		break;
 
@@ -2450,94 +2498,86 @@ static int do_scsi_command(struct fsg_dev *fsg)
 		if (!mod_data.cdrom)
 			goto unknown_cmnd;
 		fsg->data_size_from_cmnd = get_unaligned_be16(&fsg->cmnd[7]);
-		reply = check_command(fsg, 10, DATA_DIR_TO_HOST,
-				      (7<<6) | (1<<1), 1,
-				      "READ TOC");
-		if (reply == 0)
+		if ((reply = check_command(fsg, 10, DATA_DIR_TO_HOST,
+				(7<<6) | (1<<1), 1,
+				"READ TOC")) == 0)
 			reply = do_read_toc(fsg, bh);
 		break;
 
 	case SC_READ_FORMAT_CAPACITIES:
+//printf("readformat\n");
 		fsg->data_size_from_cmnd = get_unaligned_be16(&fsg->cmnd[7]);
-		reply = check_command(fsg, 10, DATA_DIR_TO_HOST,
-				      (3<<7), 1,
-				      "READ FORMAT CAPACITIES");
-		if (reply == 0)
+		if ((reply = check_command(fsg, 10, DATA_DIR_TO_HOST,
+				(3<<7), 1,
+				"READ FORMAT CAPACITIES")) == 0)
 			reply = do_read_format_capacities(fsg, bh);
 		break;
 
 	case SC_REQUEST_SENSE:
 		fsg->data_size_from_cmnd = fsg->cmnd[4];
-		reply = check_command(fsg, 6, DATA_DIR_TO_HOST,
-				      (1<<4), 0,
-				      "REQUEST SENSE");
-		if (reply == 0)
+		if ((reply = check_command(fsg, 6, DATA_DIR_TO_HOST,
+				(1<<4), 0,
+				"REQUEST SENSE")) == 0)
 			reply = do_request_sense(fsg, bh);
 		break;
 
 	case SC_START_STOP_UNIT:
 		fsg->data_size_from_cmnd = 0;
-		reply = check_command(fsg, 6, DATA_DIR_NONE,
-				      (1<<1) | (1<<4), 0,
-				      "START-STOP UNIT");
-		if (reply == 0)
+		if ((reply = check_command(fsg, 6, DATA_DIR_NONE,
+				(1<<1) | (1<<4), 0,
+				"START-STOP UNIT")) == 0)
 			reply = do_start_stop(fsg);
 		break;
 
 	case SC_SYNCHRONIZE_CACHE:
 		fsg->data_size_from_cmnd = 0;
-		reply = check_command(fsg, 10, DATA_DIR_NONE,
-				      (0xf<<2) | (3<<7), 1,
-				      "SYNCHRONIZE CACHE");
-		if (reply == 0)
+		if ((reply = check_command(fsg, 10, DATA_DIR_NONE,
+				(0xf<<2) | (3<<7), 1,
+				"SYNCHRONIZE CACHE")) == 0)
 			reply = do_synchronize_cache(fsg);
 		break;
 
 	case SC_TEST_UNIT_READY:
 		fsg->data_size_from_cmnd = 0;
 		reply = check_command(fsg, 6, DATA_DIR_NONE,
-				      0, 1,
-				      "TEST UNIT READY");
+				0, 1,
+				"TEST UNIT READY");
 		break;
 
 	/* Although optional, this command is used by MS-Windows.  We
 	 * support a minimal version: BytChk must be 0. */
 	case SC_VERIFY:
 		fsg->data_size_from_cmnd = 0;
-		reply = check_command(fsg, 10, DATA_DIR_NONE,
-				      (1<<1) | (0xf<<2) | (3<<7), 1,
-				      "VERIFY");
-		if (reply == 0)
+		if ((reply = check_command(fsg, 10, DATA_DIR_NONE,
+				(1<<1) | (0xf<<2) | (3<<7), 1,
+				"VERIFY")) == 0)
 			reply = do_verify(fsg);
 		break;
 
 	case SC_WRITE_6:
 		i = fsg->cmnd[4];
 		fsg->data_size_from_cmnd = (i == 0 ? 256 : i) << 9;
-		reply = check_command(fsg, 6, DATA_DIR_FROM_HOST,
-				      (7<<1) | (1<<4), 1,
-				      "WRITE(6)");
-		if (reply == 0)
+		if ((reply = check_command(fsg, 6, DATA_DIR_FROM_HOST,
+				(7<<1) | (1<<4), 1,
+				"WRITE(6)")) == 0)
 			reply = do_write(fsg);
 		break;
 
 	case SC_WRITE_10:
 		fsg->data_size_from_cmnd =
 				get_unaligned_be16(&fsg->cmnd[7]) << 9;
-		reply = check_command(fsg, 10, DATA_DIR_FROM_HOST,
-				      (1<<1) | (0xf<<2) | (3<<7), 1,
-				      "WRITE(10)");
-		if (reply == 0)
+		if ((reply = check_command(fsg, 10, DATA_DIR_FROM_HOST,
+				(1<<1) | (0xf<<2) | (3<<7), 1,
+				"WRITE(10)")) == 0)
 			reply = do_write(fsg);
 		break;
 
 	case SC_WRITE_12:
 		fsg->data_size_from_cmnd =
 				get_unaligned_be32(&fsg->cmnd[6]) << 9;
-		reply = check_command(fsg, 12, DATA_DIR_FROM_HOST,
-				      (1<<1) | (0xf<<2) | (0xf<<6), 1,
-				      "WRITE(12)");
-		if (reply == 0)
+		if ((reply = check_command(fsg, 12, DATA_DIR_FROM_HOST,
+				(1<<1) | (0xf<<2) | (0xf<<6), 1,
+				"WRITE(12)")) == 0)
 			reply = do_write(fsg);
 		break;
 
@@ -2549,15 +2589,14 @@ static int do_scsi_command(struct fsg_dev *fsg)
 	case SC_RELEASE:
 	case SC_RESERVE:
 	case SC_SEND_DIAGNOSTIC:
-		/* Fall through */
+		// Fall through
 
 	default:
  unknown_cmnd:
 		fsg->data_size_from_cmnd = 0;
 		sprintf(unknown, "Unknown x%02x", fsg->cmnd[0]);
-		reply = check_command(fsg, fsg->cmnd_size,
-				      DATA_DIR_UNKNOWN, 0xff, 0, unknown);
-		if (reply == 0) {
+		if ((reply = check_command(fsg, fsg->cmnd_size,
+				DATA_DIR_UNKNOWN, 0xff, 0, unknown)) == 0) {
 			fsg->curlun->sense_data = SS_INVALID_COMMAND;
 			reply = -EINVAL;
 		}
@@ -2570,14 +2609,15 @@ static int do_scsi_command(struct fsg_dev *fsg)
 
 	/* Set up the single reply buffer for finish_reply() */
 	if (reply == -EINVAL)
-		reply = 0;		/* Error reply length */
+		reply = 0;		// Error reply length
 
 	if (reply >= 0 && fsg->data_dir == DATA_DIR_TO_HOST) {
 		reply = min((u32) reply, fsg->data_size_from_cmnd);
 		bh->inreq->length = reply;
+printf("bh->inreq->length %d\n", bh->inreq->length);
 		bh->state = BUF_STATE_FULL;
 		fsg->residue -= reply;
-	}				/* Otherwise it's already set */
+	}				// Otherwise it's already set
 
 	return 0;
 }
@@ -2590,15 +2630,18 @@ static int received_cbw(struct fsg_dev *fsg, struct fsg_buffhd *bh)
 	struct usb_request		*req = bh->outreq;
 	struct fsg_bulk_cb_wrap	*cbw = req->buf;
 
+printf("%s %x %x\n",__func__, bh, req);
 	/* Was this a real packet?  Should it be ignored? */
 	if (req->status || test_bit(IGNORE_BULK_OUT, &fsg->atomic_bitflags))
+	{
+printf("%s IGNORE_BULK_OUT\n", __func__);
 		return -EINVAL;
-
+	}
 	/* Is the CBW valid? */
 	if (req->actual != USB_BULK_CB_WRAP_LEN ||
 			cbw->Signature != cpu_to_le32(
 				USB_BULK_CB_SIG)) {
-		DBG(fsg, "invalid CBW: len %u sig 0x%x\n",
+		printf("invalid CBW: len %u sig 0x%x\n",
 				req->actual,
 				le32_to_cpu(cbw->Signature));
 
@@ -2613,13 +2656,34 @@ static int received_cbw(struct fsg_dev *fsg, struct fsg_buffhd *bh)
 		 * until the next reset. */
 		wedge_bulk_in_endpoint(fsg);
 		set_bit(IGNORE_BULK_OUT, &fsg->atomic_bitflags);
+
+	if (ga_bh != 0)
+	{
+                struct bulk_cs_wrap     *csw = ga_bh->buf;
+
+                /* Store and send the Bulk-only CSW */
+                csw->Signature = cpu_to_le32(USB_BULK_CS_SIG);
+                csw->Tag = ga_tag;
+                csw->Residue = 0;
+                csw->Status = USB_STATUS_PASS;
+
+                ga_bh->inreq->length = USB_BULK_CS_WRAP_LEN;
+                ga_bh->inreq->zero = 0;
+ga_bh->inreq->buf = ga_bh->buf;
+printf("bbb %s %x %d\n", __func__, (u8 *)ga_bh, ga_bh->state);
+                start_transfer(fsg, fsg->bulk_in, ga_bh->inreq,
+                                &(ga_bh->inreq_busy), &(ga_bh->state));
+
+	}
+
+
 		return -EINVAL;
 	}
 
 	/* Is the CBW meaningful? */
 	if (cbw->Lun >= FSG_MAX_LUNS || cbw->Flags & ~USB_BULK_IN_FLAG ||
 			cbw->Length <= 0 || cbw->Length > MAX_COMMAND_SIZE) {
-		DBG(fsg, "non-meaningful CBW: lun = %u, flags = 0x%x, "
+		printf("non-meaningful CBW: lun = %u, flags = 0x%x, "
 				"cmdlen %u\n",
 				cbw->Lun, cbw->Flags, cbw->Length);
 
@@ -2632,6 +2696,7 @@ static int received_cbw(struct fsg_dev *fsg, struct fsg_buffhd *bh)
 		return -EINVAL;
 	}
 
+printf("%s\n", __func__);
 	/* Save the command for later */
 	fsg->cmnd_size = cbw->Length;
 	memcpy(fsg->cmnd, cbw->CDB, fsg->cmnd_size);
@@ -2657,7 +2722,8 @@ static int get_next_command(struct fsg_dev *fsg)
 
 		/* Wait for the next buffer to become available */
 		bh = fsg->next_buffhd_to_fill;
-		while (bh->state != BUF_STATE_EMPTY) {
+		while (bh->state != BUF_STATE_EMPTY && bh->state != BUF_STATE_FULL) {
+printf("sleep_thread %d %x\n", bh->state, bh);
 			rc = sleep_thread(fsg, __LINE__);
 			if (rc)
 				return rc;
@@ -2666,24 +2732,30 @@ static int get_next_command(struct fsg_dev *fsg)
 		/* Queue a request to read a Bulk-only CBW */
 		set_bulk_out_req_length(fsg, bh, USB_BULK_CB_WRAP_LEN);
 		bh->outreq->short_not_ok = 1;
+printf("call start_transfer, %x %x\n", (u8 *)bh, (u8 *)(fsg->bulk_out));
+bh->outreq->context = bh;
 		start_transfer(fsg, fsg->bulk_out, bh->outreq,
 				&bh->outreq_busy, &bh->state);
 
+printf("call start_transfer, %d\n", bh->state);
 		/* We will drain the buffer in software, which means we
 		 * can reuse it for the next filling.  No need to advance
 		 * next_buffhd_to_fill. */
 
 		/* Wait for the CBW to arrive */
-		while (bh->state != BUF_STATE_FULL) {
+		while (bh->state != BUF_STATE_FULL && bh->state != BUF_STATE_EMPTY ) {
+printf("Wait for the CBW to arrive\n");
 			rc = sleep_thread(fsg, __LINE__);
+printf("wake up rc %d %d\n", rc, bh->state);
 			if (rc)
 				return rc;
 		}
 		smp_rmb();
+printf("call received_cbw\n");
 		rc = received_cbw(fsg, bh);
 		bh->state = BUF_STATE_EMPTY;
 
-	} else {		/* USB_PR_CB or USB_PR_CBI */
+	} else {		// USB_PR_CB or USB_PR_CBI
 
 		/* Wait for the next command to arrive */
 		while (fsg->cbbuf_cmnd_size == 0) {
@@ -2747,6 +2819,7 @@ static int do_set_interface(struct fsg_dev *fsg, int altsetting)
 
 	if (fsg->running)
 		DBG(fsg, "reset interface\n");
+//printf("reset interface\n");
 
 reset:
 	/* Deallocate the requests */
@@ -2790,15 +2863,13 @@ reset:
 	/* Enable the endpoints */
 	d = fsg_ep_desc(fsg->gadget,
 			&fsg_fs_bulk_in_desc, &fsg_hs_bulk_in_desc);
-	rc = enable_endpoint(fsg, fsg->bulk_in, d);
-	if (rc)
+	if ((rc = enable_endpoint(fsg, fsg->bulk_in, d)) != 0)
 		goto reset;
 	fsg->bulk_in_enabled = 1;
 
 	d = fsg_ep_desc(fsg->gadget,
 			&fsg_fs_bulk_out_desc, &fsg_hs_bulk_out_desc);
-	rc = enable_endpoint(fsg, fsg->bulk_out, d);
-	if (rc)
+	if ((rc = enable_endpoint(fsg, fsg->bulk_out, d)) != 0)
 		goto reset;
 	fsg->bulk_out_enabled = 1;
 	fsg->bulk_out_maxpacket = le16_to_cpu(d->wMaxPacketSize);
@@ -2807,8 +2878,7 @@ reset:
 	if (transport_is_cbi()) {
 		d = fsg_ep_desc(fsg->gadget,
 				&fsg_fs_intr_in_desc, &fsg_hs_intr_in_desc);
-		rc = enable_endpoint(fsg, fsg->intr_in, d);
-		if (rc)
+		if ((rc = enable_endpoint(fsg, fsg->intr_in, d)) != 0)
 			goto reset;
 		fsg->intr_in_enabled = 1;
 	}
@@ -2817,11 +2887,9 @@ reset:
 	for (i = 0; i < FSG_NUM_BUFFERS; ++i) {
 		struct fsg_buffhd	*bh = &fsg->buffhds[i];
 
-		rc = alloc_request(fsg, fsg->bulk_in, &bh->inreq);
-		if (rc)
+		if ((rc = alloc_request(fsg, fsg->bulk_in, &bh->inreq)) != 0)
 			goto reset;
-		rc = alloc_request(fsg, fsg->bulk_out, &bh->outreq);
-		if (rc)
+		if ((rc = alloc_request(fsg, fsg->bulk_out, &bh->outreq)) != 0)
 			goto reset;
 		bh->inreq->buf = bh->outreq->buf = bh->buf;
 		bh->inreq->context = bh->outreq->context = bh;
@@ -2829,8 +2897,7 @@ reset:
 		bh->outreq->complete = bulk_out_complete;
 	}
 	if (transport_is_cbi()) {
-		rc = alloc_request(fsg, fsg->intr_in, &fsg->intreq);
-		if (rc)
+		if ((rc = alloc_request(fsg, fsg->intr_in, &fsg->intreq)) != 0)
 			goto reset;
 		fsg->intreq->complete = intr_in_complete;
 	}
@@ -2849,11 +2916,12 @@ reset:
  * It's also responsible for power management interactions.  Some
  * configurations might not work with our current power sources.
  * For now we just assume the gadget is always self-powered.
- */
+*/
 static int do_set_config(struct fsg_dev *fsg, u8 new_config)
 {
 	int	rc = 0;
 
+//printf("reset config\n");
 	/* Disable the single interface */
 	if (fsg->config != 0) {
 		DBG(fsg, "reset config\n");
@@ -2864,25 +2932,16 @@ static int do_set_config(struct fsg_dev *fsg, u8 new_config)
 	/* Enable the interface */
 	if (new_config != 0) {
 		fsg->config = new_config;
-		rc = do_set_interface(fsg, 0);
-		if (rc) {
-			fsg->config = 0;	/* Reset on errors */
+		if ((rc = do_set_interface(fsg, 0)) != 0) {
+			fsg->config = 0;	// Reset on errors
 		} else {
 			char *speed;
 
 			switch (fsg->gadget->speed) {
-			case USB_SPEED_LOW:
-				speed = "low";
-				break;
-			case USB_SPEED_FULL:
-				speed = "full";
-				break;
-			case USB_SPEED_HIGH:
-				speed = "high";
-				break;
-			default:
-				speed = "?";
-				break;
+			case USB_SPEED_LOW:	speed = "low";	break;
+			case USB_SPEED_FULL:	speed = "full";	break;
+			case USB_SPEED_HIGH:	speed = "high";	break;
+			default:		speed = "?";	break;
 			}
 			INFO(fsg, "%s speed config #%d\n", speed, fsg->config);
 		}
@@ -2981,6 +3040,7 @@ static void handle_exception(struct fsg_dev *fsg)
 	spin_unlock_irq(&fsg->lock);
 
 	/* Carry out any extra actions required for the exception */
+printf("old_state %d\n", old_state);
 	switch (old_state) {
 	default:
 		break;
@@ -3002,25 +3062,25 @@ static void handle_exception(struct fsg_dev *fsg)
 
 		if (transport_is_bbb()) {
 			if (fsg->ep0_req_tag == exception_req_tag)
-				ep0_queue(fsg);	/* Complete the status stage */
+				ep0_queue(fsg);	// Complete the status stage
 
 		} else if (transport_is_cbi())
-			send_status(fsg);	/* Status by interrupt pipe */
+			send_status(fsg);	// Status by interrupt pipe
 
 		/* Technically this should go here, but it would only be
 		 * a waste of time.  Ditto for the INTERFACE_CHANGE and
 		 * CONFIG_CHANGE cases. */
-		/* for (i = 0; i < fsg->nluns; ++i) */
-		/* fsg->luns[i].unit_attention_data = SS_RESET_OCCURRED; */
+		// for (i = 0; i < fsg->nluns; ++i)
+		//	fsg->luns[i].unit_attention_data = SS_RESET_OCCURRED;
 		break;
 
 	case FSG_STATE_INTERFACE_CHANGE:
 		rc = do_set_interface(fsg, 0);
 		if (fsg->ep0_req_tag != exception_req_tag)
 			break;
-		if (rc != 0)			/* STALL on errors */
+		if (rc != 0)			// STALL on errors
 			fsg_set_halt(fsg, fsg->ep0);
-		else				/* Complete the status stage */
+		else				// Complete the status stage
 			ep0_queue(fsg);
 		break;
 
@@ -3028,23 +3088,23 @@ static void handle_exception(struct fsg_dev *fsg)
 		rc = do_set_config(fsg, new_config);
 		if (fsg->ep0_req_tag != exception_req_tag)
 			break;
-		if (rc != 0)			/* STALL on errors */
+		if (rc != 0)			// STALL on errors
 			fsg_set_halt(fsg, fsg->ep0);
-		else				/* Complete the status stage */
+		else				// Complete the status stage
 			ep0_queue(fsg);
 		break;
 
 	case FSG_STATE_DISCONNECT:
 		for (i = 0; i < fsg->nluns; ++i)
 			fsg_lun_fsync_sub(fsg->luns + i);
-		do_set_config(fsg, 0);		/* Unconfigured state */
+		do_set_config(fsg, 0);		// Unconfigured state
 		break;
 
 	case FSG_STATE_EXIT:
 	case FSG_STATE_TERMINATED:
-		do_set_config(fsg, 0);			/* Free resources */
+		do_set_config(fsg, 0);			// Free resources
 		spin_lock_irq(&fsg->lock);
-		fsg->state = FSG_STATE_TERMINATED;	/* Stop the thread */
+		fsg->state = FSG_STATE_TERMINATED;	// Stop the thread
 		spin_unlock_irq(&fsg->lock);
 		break;
 	}
@@ -3053,7 +3113,7 @@ static void handle_exception(struct fsg_dev *fsg)
 
 /*-------------------------------------------------------------------------*/
 
-int fsg_main_thread(void *_fsg)
+int fsg_main_thread(void * _fsg)
 {
 	int ret;
 	struct fsg_dev		*fsg = the_fsg;
@@ -3071,20 +3131,23 @@ int fsg_main_thread(void *_fsg)
 	/* Arrange for userspace references to be interpreted as kernel
 	 * pointers.  That way we can pass a kernel pointer to a routine
 	 * that expects a __user pointer and it will work okay. */
-	/* et_fs(get_ds()); */
+	//set_fs(get_ds());
 
 	/* The main loop */
 	do {
 		if (exception_in_progress(fsg)) {
+printf("handle exception\n");
 			handle_exception(fsg);
 			continue;
 		}
 
 		if (!fsg->running) {
-			/* leep_thread(fsg, __LINE__); */
+printf("handle running\n");
+			sleep_thread(fsg, __LINE__);
 			continue;
 		}
 
+printf("get_next_command\n");
 		ret = get_next_command(fsg);
 		if (ret) {
 			/* Check ig USB cable has been detached */
@@ -3099,16 +3162,18 @@ int fsg_main_thread(void *_fsg)
 			fsg->state = FSG_STATE_DATA_PHASE;
 		spin_unlock_irq(&fsg->lock);
 
-		if (do_scsi_command(fsg) || finish_reply(fsg))
+		if (do_scsi_command(fsg) || finish_reply(fsg)) {
 			continue;
+		}
 
 		spin_lock_irq(&fsg->lock);
 		if (!exception_in_progress(fsg))
 			fsg->state = FSG_STATE_STATUS_PHASE;
 		spin_unlock_irq(&fsg->lock);
 
-		if (send_status(fsg))
+		if (send_status(fsg)) {
 			continue;
+		}
 
 		spin_lock_irq(&fsg->lock);
 		if (!exception_in_progress(fsg))
@@ -3123,8 +3188,9 @@ int fsg_main_thread(void *_fsg)
 	/* If we are exiting because of a signal, unregister the
 	 * gadget driver. */
 	if (test_and_clear_bit(REGISTERED, &fsg->atomic_bitflags))
-		; /* sb_gadget_unregister_driver(&fsg_driver); */
+		; //usb_gadget_unregister_driver(&fsg_driver);
 
+printf("exiting main thread...\n");
 	/* Let the unbind and cleanup routines know the thread has exited */
 	complete_and_exit(&fsg->thread_notifier, 0);
 	return 0;
@@ -3173,8 +3239,8 @@ static void /* __init_or_exit */ fsg_unbind(struct usb_gadget *gadget)
 	for (i = 0; i < fsg->nluns; ++i) {
 		curlun = &fsg->luns[i];
 		if (curlun->registered) {
-			/* evice_remove_file(&curlun->dev, &dev_attr_ro); */
-			/* evice_remove_file(&curlun->dev, &dev_attr_file); */
+			//device_remove_file(&curlun->dev, &dev_attr_ro);
+			//device_remove_file(&curlun->dev, &dev_attr_file);
 			fsg_lun_close(curlun);
 			/* device_unregister(&curlun->dev); */
 			curlun->registered = 0;
@@ -3223,8 +3289,8 @@ static int __init check_parameters(struct fsg_dev *fsg)
 	if (gadget_is_at91(fsg->gadget))
 		mod_data.can_stall = 0;
 
-	if (mod_data.release == 0xffff) {	/* Parameter wasn't set */
-		gcnum = 1 ;/* usb_gadget_controller_number(fsg->gadget); */
+	if (mod_data.release == 0xffff) {	// Parameter wasn't set
+		gcnum = 1 ;// usb_gadget_controller_number(fsg->gadget);
 		if (gcnum >= 0)
 			mod_data.release = 0x0300 + gcnum;
 		else {
@@ -3306,29 +3372,30 @@ static int __ref fsg_bind(struct usb_gadget *gadget)
 	fsg->ep0 = gadget->ep0;
 	fsg->ep0->driver_data = fsg;
 
-	rc = check_parameters(fsg);
-	if (rc)
+	if ((rc = check_parameters(fsg)) != 0) {
+		printf("%s: check_parameters\n", __func__);
 		goto out;
+	}
 
-	if (mod_data.removable) {	/* Enable the store_xxx attributes */
-		/* ev_attr_file.attr.mode = 0644; */
-		/* ev_attr_file.store = fsg_store_file; */
+	if (mod_data.removable) {	// Enable the store_xxx attributes
+		//dev_attr_file.attr.mode = 0644;
+		//dev_attr_file.store = fsg_store_file;
 		if (!mod_data.cdrom) {
-			/* ev_attr_ro.attr.mode = 0644; */
-			/* ev_attr_ro.store = fsg_store_ro; */
+			//dev_attr_ro.attr.mode = 0644;
+			//dev_attr_ro.store = fsg_store_ro;
 		}
 	}
 
 	/* Only for removable media? */
-	/* ev_attr_nofua.attr.mode = 0644; */
-	/* ev_attr_nofua.store = fsg_store_nofua; */
+	//dev_attr_nofua.attr.mode = 0644;
+	//dev_attr_nofua.store = fsg_store_nofua;
 
 	/* Find out how many LUNs there should be */
 	i = mod_data.nluns;
 	if (i == 0)
 		i = max(mod_data.num_filenames, 1u);
 	if (i > FSG_MAX_LUNS) {
-		ERROR(fsg, "invalid number of LUNs: %d\n", i);
+		printf("invalid number of LUNs: %d\n", i);
 		rc = -EINVAL;
 		goto out;
 	}
@@ -3337,6 +3404,7 @@ static int __ref fsg_bind(struct usb_gadget *gadget)
 	 * LUN devices in sysfs. */
 	fsg->luns = kzalloc(i * sizeof(struct fsg_lun), GFP_KERNEL);
 	if (!fsg->luns) {
+		printf("%s: kzalloc\n", __func__);
 		rc = -ENOMEM;
 		goto out;
 	}
@@ -3353,46 +3421,61 @@ static int __ref fsg_bind(struct usb_gadget *gadget)
 		dev_set_name(&curlun->dev,"%s-lun%d",
 			     dev_name(&gadget->dev), i);
 
-		rc = device_register(&curlun->dev);
-		if (rc) {
-			INFO(fsg, "failed to register LUN%d: %d\n", i, rc);
+		if ((rc = device_register(&curlun->dev)) != 0) {
+			printf("failed to register LUN%d: %d\n", i, rc);
 			goto out;
 		}
-
-		rc = device_create_file(&curlun->dev, &dev_attr_ro);
-		rc |= device_create_file(&curlun->dev, &dev_attr_nofua);
-		rc |= device_create_file(&curlun->dev, &dev_attr_file);
-
-		if (rc)/* device_unregister(&curlun->dev); */
+		if ((rc = device_create_file(&curlun->dev,
+					&dev_attr_ro)) != 0 ||
+				(rc = device_create_file(&curlun->dev,
+					&dev_attr_nofua)) != 0 ||
+				(rc = device_create_file(&curlun->dev,
+					&dev_attr_file)) != 0) {
+			/* device_unregister(&curlun->dev); */
+			printf("%s: device_create_file\n", __func__);
 			goto out;
-
+		}
 		curlun->registered = 1;
 		kref_get(&fsg->ref);
 
-		rc = fsg_lun_open(curlun, mod_data.file[i]);
-		if (rc)
+//printf("fsg_lun_open %d\n", i);
+		if ((rc = fsg_lun_open(curlun,
+		                       mod_data.file[i])) != 0) {
+			//printf("%s: fsg_lun_open\n", __func__);
 			goto out;
+		}
 	}
 
+//printf("find all endpoints\n");
 	/* Find all the endpoints we will use */
 	usb_ep_autoconfig_reset(gadget);
 	ep = usb_ep_autoconfig(gadget, &fsg_fs_bulk_in_desc);
+//printf("usb_ep_autoconfig bulk in\n");
 	if (!ep)
+	{
+		printf("%s: usb_ep_autoconfig in\n", __func__);		
 		goto autoconf_fail;
-	ep->driver_data = fsg;		/* claim the endpoint */
+	}
+	ep->driver_data = fsg;		// claim the endpoint
 	fsg->bulk_in = ep;
 
 	ep = usb_ep_autoconfig(gadget, &fsg_fs_bulk_out_desc);
 	if (!ep)
+	{
+		printf("%s: usb_ep_autoconfig out\n", __func__);		
 		goto autoconf_fail;
-	ep->driver_data = fsg;		/* claim the endpoint */
+	}
+	ep->driver_data = fsg;		// claim the endpoint
 	fsg->bulk_out = ep;
 
+if (fsg_fs_bulk_out_desc.bEndpointAddress != 0x1)
+	fsg_fs_bulk_out_desc.bEndpointAddress = 0x1;
+
 	if (transport_is_cbi()) {
 		ep = usb_ep_autoconfig(gadget, &fsg_fs_intr_in_desc);
 		if (!ep)
 			goto autoconf_fail;
-		ep->driver_data = fsg;		/* claim the endpoint */
+		ep->driver_data = fsg;		// claim the endpoint
 		fsg->intr_in = ep;
 	}
 
@@ -3402,12 +3485,13 @@ static int __ref fsg_bind(struct usb_gadget *gadget)
 	device_desc.idProduct = cpu_to_le16(mod_data.product);
 	device_desc.bcdDevice = cpu_to_le16(mod_data.release);
 
-	i = (transport_is_cbi() ? 3 : 2);	/* Number of endpoints */
+	i = (transport_is_cbi() ? 3 : 2);	// Number of endpoints
 	fsg_intf_desc.bNumEndpoints = i;
 	fsg_intf_desc.bInterfaceSubClass = mod_data.protocol_type;
 	fsg_intf_desc.bInterfaceProtocol = mod_data.transport_type;
 	fsg_fs_function[i + FSG_FS_FUNCTION_PRE_EP_ENTRIES] = NULL;
 
+printf("bEndpoint %x %x %x\n",fsg_fs_bulk_in_desc.bEndpointAddress, fsg_fs_bulk_out_desc.bEndpointAddress, fsg_fs_intr_in_desc.bEndpointAddress);
 	if (gadget_is_dualspeed(gadget)) {
 		fsg_hs_function[i + FSG_HS_FUNCTION_PRE_EP_ENTRIES] = NULL;
 
@@ -3428,6 +3512,7 @@ static int __ref fsg_bind(struct usb_gadget *gadget)
 
 	rc = -ENOMEM;
 
+//printf("Allocate the request and buffer for endpoint 0\n");
 	/* Allocate the request and buffer for endpoint 0 */
 	fsg->ep0req = req = usb_ep_alloc_request(fsg->ep0, GFP_KERNEL);
 	if (!req)
@@ -3461,19 +3546,20 @@ static int __ref fsg_bind(struct usb_gadget *gadget)
 
 	fsg->thread_task = kthread_create(fsg_main_thread, fsg,
 			"file-storage-gadget");
-	if (IS_ERR(fsg->thread_task))
+	if (IS_ERR(fsg->thread_task)) {
 		rc = PTR_ERR(fsg->thread_task);
+	}
 
-	INFO(fsg, DRIVER_DESC ", version: " DRIVER_VERSION "\n");
-	INFO(fsg, "Number of LUNs=%d\n", fsg->nluns);
+	printf(DRIVER_DESC ", version: " DRIVER_VERSION "\n");
+	printf("Number of LUNs=%d\n", fsg->nluns);
 
-	DBG(fsg, "transport=%s (x%02x)\n",
+	printf("transport=%s (x%02x)\n",
 			mod_data.transport_name, mod_data.transport_type);
-	DBG(fsg, "protocol=%s (x%02x)\n",
+	printf("protocol=%s (x%02x)\n",
 			mod_data.protocol_name, mod_data.protocol_type);
-	DBG(fsg, "VendorID=x%04x, ProductID=x%04x, Release=x%04x\n",
+	printf("VendorID=x%04x, ProductID=x%04x, Release=x%04x\n",
 			mod_data.vendor, mod_data.product, mod_data.release);
-	DBG(fsg, "removable=%d, stall=%d, cdrom=%d, buflen=%u\n",
+	printf("removable=%d, stall=%d, cdrom=%d, buflen=%u\n",
 			mod_data.removable, mod_data.can_stall,
 			mod_data.cdrom, mod_data.buflen);
 	set_bit(REGISTERED, &fsg->atomic_bitflags);
@@ -3483,11 +3569,12 @@ static int __ref fsg_bind(struct usb_gadget *gadget)
 	return 0;
 
 autoconf_fail:
-	ERROR(fsg, "unable to autoconfigure all endpoints\n");
+	printf("unable to autoconfigure all endpoints\n");
 	rc = -ENOTSUPP;
 
 out:
-	fsg->state = FSG_STATE_TERMINATED;	/* The thread is dead */
+	printf("%s: out\n",__func__);
+	fsg->state = FSG_STATE_TERMINATED;	// The thread is dead
 	fsg_unbind(gadget);
 	complete(&fsg->thread_notifier);
 	return rc;
@@ -3552,14 +3639,14 @@ int __init fsg_init(struct ums_board_info* _ums)
 	struct fsg_dev	*fsg;
 
 	ums_info = _ums;
-	rc = fsg_alloc();
-	if (rc)
+	if ((rc = fsg_alloc()) != 0)
 		return rc;
 	fsg = the_fsg;
-
-	rc = usb_gadget_register_driver(&fsg_driver);
-	if (rc)
+//printf("call usb_gadget_register_driver\n");
+	if ((rc = usb_gadget_register_driver(&fsg_driver)) != 0)
 		kref_put(&fsg->ref, fsg_release);
+//printf("call usb_gadget_connect\n");
+
 	usb_gadget_connect(the_fsg->gadget);
 
 	return rc;
-- 
1.7.2.3

