Kill usage of USB_VENDOR_FOO and USB_PRODUCT_BAR defines mostly using two
[dragonfly.git] / sys / dev / usbmisc / umass / umass.c
1 /*-
2  * Copyright (c) 1999 MAEKAWA Masahide <bishop@rr.iij4u.or.jp>,
3  *                    Nick Hibma <n_hibma@freebsd.org>
4  * All rights reserved.
5  *
6  * Redistribution and use in source and binary forms, with or without
7  * modification, are permitted provided that the following conditions
8  * are met:
9  * 1. Redistributions of source code must retain the above copyright
10  *    notice, this list of conditions and the following disclaimer.
11  * 2. Redistributions in binary form must reproduce the above copyright
12  *    notice, this list of conditions and the following disclaimer in the
13  *    documentation and/or other materials provided with the distribution.
14  *
15  * THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND
16  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
17  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
18  * ARE DISCLAIMED.  IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE
19  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
20  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
21  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
22  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
23  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
24  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
25  * SUCH DAMAGE.
26  *
27  * $NetBSD: umass.c,v 1.28 2000/04/02 23:46:53 augustss Exp $
28  * $FreeBSD: src/sys/dev/usb/umass.c,v 1.96 2003/12/19 12:19:11 sanpei Exp $
29  * $DragonFly: src/sys/dev/usbmisc/umass/umass.c,v 1.28 2007/11/05 13:32:28 hasso Exp $
30  */
31
32 /*
33  * Universal Serial Bus Mass Storage Class specs:
34  * http://www.usb.org/developers/data/devclass/usbmassover_11.pdf
35  * http://www.usb.org/developers/data/devclass/usbmassbulk_10.pdf
36  * http://www.usb.org/developers/data/devclass/usbmass-cbi10.pdf
37  * http://www.usb.org/developers/data/devclass/usbmass-ufi10.pdf
38  */
39
40 /*
41  * Ported to NetBSD by Lennart Augustsson <augustss@netbsd.org>.
42  * Parts of the code written my Jason R. Thorpe <thorpej@shagadelic.org>.
43  */
44
45 /*
46  * The driver handles 3 Wire Protocols
47  * - Command/Bulk/Interrupt (CBI)
48  * - Command/Bulk/Interrupt with Command Completion Interrupt (CBI with CCI)
49  * - Mass Storage Bulk-Only (BBB)
50  *   (BBB refers Bulk/Bulk/Bulk for Command/Data/Status phases)
51  *
52  * Over these wire protocols it handles the following command protocols
53  * - SCSI
54  * - UFI (floppy command set)
55  * - 8070i (ATAPI)
56  *
57  * UFI and 8070i (ATAPI) are transformed versions of the SCSI command set. The
58  * sc->transform method is used to convert the commands into the appropriate
59  * format (if at all necessary). For example, UFI requires all commands to be
60  * 12 bytes in length amongst other things.
61  *
62  * The source code below is marked and can be split into a number of pieces
63  * (in this order):
64  *
65  * - probe/attach/detach
66  * - generic transfer routines
67  * - BBB
68  * - CBI
69  * - CBI_I (in addition to functions from CBI)
70  * - CAM (Common Access Method)
71  * - SCSI
72  * - UFI
73  * - 8070i (ATAPI)
74  *
75  * The protocols are implemented using a state machine, for the transfers as
76  * well as for the resets. The state machine is contained in umass_*_state.
77  * The state machine is started through either umass_*_transfer or
78  * umass_*_reset.
79  *
80  * The reason for doing this is a) CAM performs a lot better this way and b) it
81  * avoids using tsleep from interrupt context (for example after a failed
82  * transfer).
83  */
84
85 /*
86  * The SCSI related part of this driver has been derived from the
87  * dev/ppbus/vpo.c driver, by Nicolas Souchu (nsouch@freebsd.org).
88  *
89  * The CAM layer uses so called actions which are messages sent to the host
90  * adapter for completion. The actions come in through umass_cam_action. The
91  * appropriate block of routines is called depending on the transport protocol
92  * in use. When the transfer has finished, these routines call
93  * umass_cam_cb again to complete the CAM command.
94  */
95
96 /*
97  * XXX Currently CBI with CCI is not supported because it bombs the system
98  *     when the device is detached (low frequency interrupts are detached
99  *     too late.
100  */
101 #undef CBI_I
102
103 #include <sys/param.h>
104 #include <sys/systm.h>
105 #include <sys/kernel.h>
106 #include <sys/module.h>
107 #include <sys/bus.h>
108 #include <sys/sysctl.h>
109
110 #include <bus/usb/usb.h>
111 #include <bus/usb/usbdi.h>
112 #include <bus/usb/usbdi_util.h>
113 #include <bus/usb/usbdevs.h>
114
115 #include <bus/cam/cam.h>
116 #include <bus/cam/cam_ccb.h>
117 #include <bus/cam/cam_sim.h>
118 #include <bus/cam/cam_xpt_sim.h>
119 #include <bus/cam/scsi/scsi_all.h>
120 #include <bus/cam/scsi/scsi_da.h>
121 #include <bus/cam/scsi/scsi_cd.h>
122 #include <bus/cam/scsi/scsi_ch.h>
123 #include <dev/disk/ata/atapi-all.h>
124
125 #include <bus/cam/cam_periph.h>
126
127 #ifdef USB_DEBUG
128 #define DIF(m, x)       if (umassdebug & (m)) do { x ; } while (0)
129 #define DPRINTF(m, x)   if (umassdebug & (m)) kprintf x
130 #define UDMASS_GEN      0x00010000      /* general */
131 #define UDMASS_SCSI     0x00020000      /* scsi */
132 #define UDMASS_UFI      0x00040000      /* ufi command set */
133 #define UDMASS_ATAPI    0x00080000      /* 8070i command set */
134 #define UDMASS_CMD      (UDMASS_SCSI|UDMASS_UFI|UDMASS_ATAPI)
135 #define UDMASS_USB      0x00100000      /* USB general */
136 #define UDMASS_BBB      0x00200000      /* Bulk-Only transfers */
137 #define UDMASS_CBI      0x00400000      /* CBI transfers */
138 #define UDMASS_WIRE     (UDMASS_BBB|UDMASS_CBI)
139 #define UDMASS_ALL      0xffff0000      /* all of the above */
140 int umassdebug = 0;
141 SYSCTL_NODE(_hw_usb, OID_AUTO, umass, CTLFLAG_RW, 0, "USB umass");
142 SYSCTL_INT(_hw_usb_umass, OID_AUTO, debug, CTLFLAG_RW,
143            &umassdebug, 0, "umass debug level");
144 #else
145 #define DIF(m, x)       /* nop */
146 #define DPRINTF(m, x)   /* nop */
147 #endif
148
149
150 /* Generic definitions */
151
152 /* Direction for umass_*_transfer */
153 #define DIR_NONE        0
154 #define DIR_IN          1
155 #define DIR_OUT         2
156
157 /* device name */
158 #define DEVNAME         "umass"
159 #define DEVNAME_SIM     "umass-sim"
160
161 #define UMASS_MAX_TRANSFER_SIZE         65536
162 #define UMASS_DEFAULT_TRANSFER_SPEED    1000
163 #define UMASS_FLOPPY_TRANSFER_SPEED     20
164
165 #define UMASS_TIMEOUT                   5000 /* msecs */
166
167 /* CAM specific definitions */
168
169 #define UMASS_SCSIID_MAX        1       /* maximum number of drives expected */
170 #define UMASS_SCSIID_HOST       UMASS_SCSIID_MAX
171
172 #define MS_TO_TICKS(ms) ((ms) * hz / 1000)
173
174
175 /* Bulk-Only features */
176
177 #define UR_BBB_RESET            0xff            /* Bulk-Only reset */
178 #define UR_BBB_GET_MAX_LUN      0xfe            /* Get maximum lun */
179
180 /* Command Block Wrapper */
181 typedef struct {
182         uDWord          dCBWSignature;
183 #       define CBWSIGNATURE     0x43425355
184         uDWord          dCBWTag;
185         uDWord          dCBWDataTransferLength;
186         uByte           bCBWFlags;
187 #       define CBWFLAGS_OUT     0x00
188 #       define CBWFLAGS_IN      0x80
189         uByte           bCBWLUN;
190         uByte           bCDBLength;
191 #       define CBWCDBLENGTH     16
192         uByte           CBWCDB[CBWCDBLENGTH];
193 } umass_bbb_cbw_t;
194 #define UMASS_BBB_CBW_SIZE      31
195
196 /* Command Status Wrapper */
197 typedef struct {
198         uDWord          dCSWSignature;
199 #       define CSWSIGNATURE     0x53425355
200 #       define CSWSIGNATURE_OLYMPUS_C1  0x55425355
201         uDWord          dCSWTag;
202         uDWord          dCSWDataResidue;
203         uByte           bCSWStatus;
204 #       define CSWSTATUS_GOOD   0x0
205 #       define CSWSTATUS_FAILED 0x1
206 #       define CSWSTATUS_PHASE  0x2
207 } umass_bbb_csw_t;
208 #define UMASS_BBB_CSW_SIZE      13
209
210 /* CBI features */
211
212 #define UR_CBI_ADSC     0x00
213
214 typedef unsigned char umass_cbi_cbl_t[16];      /* Command block */
215
216 typedef union {
217         struct {
218                 unsigned char   type;
219                 #define IDB_TYPE_CCI            0x00
220                 unsigned char   value;
221                 #define IDB_VALUE_PASS          0x00
222                 #define IDB_VALUE_FAIL          0x01
223                 #define IDB_VALUE_PHASE         0x02
224                 #define IDB_VALUE_PERSISTENT    0x03
225                 #define IDB_VALUE_STATUS_MASK   0x03
226         } common;
227
228         struct {
229                 unsigned char   asc;
230                 unsigned char   ascq;
231         } ufi;
232 } umass_cbi_sbl_t;
233
234
235
236 struct umass_softc;             /* see below */
237
238 typedef void (*transfer_cb_f)   (struct umass_softc *sc, void *priv,
239                                 int residue, int status);
240 #define STATUS_CMD_OK           0       /* everything ok */
241 #define STATUS_CMD_UNKNOWN      1       /* will have to fetch sense */
242 #define STATUS_CMD_FAILED       2       /* transfer was ok, command failed */
243 #define STATUS_WIRE_FAILED      3       /* couldn't even get command across */
244
245 typedef void (*wire_reset_f)    (struct umass_softc *sc, int status);
246 typedef void (*wire_transfer_f) (struct umass_softc *sc, int lun,
247                                 void *cmd, int cmdlen, void *data, int datalen,
248                                 int dir, transfer_cb_f cb, void *priv);
249 typedef void (*wire_state_f)    (usbd_xfer_handle xfer,
250                                 usbd_private_handle priv, usbd_status err);
251
252 typedef int (*command_transform_f)      (struct umass_softc *sc,
253                                 unsigned char *cmd, int cmdlen,
254                                 unsigned char **rcmd, int *rcmdlen);
255
256
257 struct umass_devdescr_t {
258         u_int32_t       vendor;
259         u_int32_t       product;
260         u_int32_t       release;
261 #       define WILDCARD_ID      0xffffffff
262 #       define EOT_ID           0xfffffffe
263
264         /* wire and command protocol */
265         u_int16_t       proto;
266 #       define UMASS_PROTO_BBB          0x0001  /* USB wire protocol */
267 #       define UMASS_PROTO_CBI          0x0002
268 #       define UMASS_PROTO_CBI_I        0x0004
269 #       define UMASS_PROTO_WIRE         0x00ff  /* USB wire protocol mask */
270 #       define UMASS_PROTO_SCSI         0x0100  /* command protocol */
271 #       define UMASS_PROTO_ATAPI        0x0200
272 #       define UMASS_PROTO_UFI          0x0400
273 #       define UMASS_PROTO_RBC          0x0800
274 #       define UMASS_PROTO_COMMAND      0xff00  /* command protocol mask */
275
276         /* Device specific quirks */
277         u_int16_t       quirks;
278 #       define NO_QUIRKS                0x0000
279         /* The drive does not support Test Unit Ready. Convert to Start Unit
280          */
281 #       define NO_TEST_UNIT_READY       0x0001
282         /* The drive does not reset the Unit Attention state after REQUEST
283          * SENSE has been sent. The INQUIRY command does not reset the UA
284          * either, and so CAM runs in circles trying to retrieve the initial
285          * INQUIRY data.
286          */
287 #       define RS_NO_CLEAR_UA           0x0002
288         /* The drive does not support START STOP.  */
289 #       define NO_START_STOP            0x0004
290         /* Don't ask for full inquiry data (255b).  */
291 #       define FORCE_SHORT_INQUIRY      0x0008
292         /* Needs to be initialised the Shuttle way */
293 #       define SHUTTLE_INIT             0x0010
294         /* Drive needs to be switched to alternate iface 1 */
295 #       define ALT_IFACE_1              0x0020
296         /* Drive does not do 1Mb/s, but just floppy speeds (20kb/s) */
297 #       define FLOPPY_SPEED             0x0040
298         /* The device can't count and gets the residue of transfers wrong */
299 #       define IGNORE_RESIDUE           0x0080
300         /* No GetMaxLun call */
301 #       define NO_GETMAXLUN             0x0100
302         /* The device uses a weird CSWSIGNATURE. */
303 #       define WRONG_CSWSIG             0x0200
304         /* Device cannot handle INQUIRY so fake a generic response */
305 #       define NO_INQUIRY               0x0400
306         /* Device cannot handle INQUIRY EVPD, return CHECK CONDITION */
307 #       define NO_INQUIRY_EVPD          0x0800
308 };
309
310 static struct umass_devdescr_t umass_devdescrs[] = {
311         /* All Asahi Optical products */
312         { .vendor = 0x0a17, .product = WILDCARD_ID, .release = WILDCARD_ID,
313           .proto  = UMASS_PROTO_ATAPI | UMASS_PROTO_CBI_I,
314           .quirks = RS_NO_CLEAR_UA
315         },
316         /* Fujiphoto mass storage products */
317         { .vendor = 0x04cb, .product = 0x0100, .release = WILDCARD_ID,
318           .proto  = UMASS_PROTO_ATAPI | UMASS_PROTO_CBI_I,
319           .quirks = RS_NO_CLEAR_UA
320         },
321         /* Genesys Logic GL641USB USB-IDE Bridge */
322         { .vendor = 0x05e3, .product = 0x0702, .release = WILDCARD_ID,
323           .proto  = UMASS_PROTO_SCSI | UMASS_PROTO_BBB,
324           .quirks = FORCE_SHORT_INQUIRY | NO_START_STOP | IGNORE_RESIDUE
325         },
326         /* Genesys Logic GL641USB CompactFlash Card Reader */
327         { .vendor = 0x05e3, .product = 0x0700, .release = WILDCARD_ID,
328           .proto  = UMASS_PROTO_SCSI | UMASS_PROTO_BBB,
329           .quirks = FORCE_SHORT_INQUIRY | NO_START_STOP | IGNORE_RESIDUE
330         },
331         /* Hitachi DVDCAM USB HS Interface */
332         { .vendor = 0x04a4, .product = 0x001e, .release = WILDCARD_ID,
333           .proto  = UMASS_PROTO_ATAPI | UMASS_PROTO_CBI_I,
334           .quirks = NO_INQUIRY
335         },
336         /* HP CD-Writer Plus 8200e */
337         { .vendor = 0x03f0, .product = 0x0207, .release = WILDCARD_ID,
338           .proto  = UMASS_PROTO_ATAPI | UMASS_PROTO_CBI_I,
339           .quirks = NO_TEST_UNIT_READY | NO_START_STOP
340         },
341         /* In-System USB cable */
342         { .vendor = 0x05ab, .product = 0x081a, .release = WILDCARD_ID,
343           .proto  = UMASS_PROTO_ATAPI | UMASS_PROTO_CBI,
344           .quirks = NO_TEST_UNIT_READY | NO_START_STOP | ALT_IFACE_1
345         },
346         /* Iomega Zip 100 */
347         { .vendor = 0x059b, .product = 0x0001, .release = WILDCARD_ID,
348           /* XXX This is not correct as there are Zip drives that use ATAPI. */
349           .proto  = UMASS_PROTO_SCSI | UMASS_PROTO_BBB,
350           .quirks = NO_TEST_UNIT_READY
351         },
352         /* Logitech DVD Multi-plus unit LDR-H443U2 */
353         { .vendor = 0x0789, .product = 0x00b3, .release = WILDCARD_ID,
354           .proto  = UMASS_PROTO_SCSI | UMASS_PROTO_BBB,
355           .quirks = NO_QUIRKS
356         },
357         /* Melco USB-IDE Bridge: DUB-PxxG */
358         { .vendor = 0x0411, .product = 0x001c, .release = WILDCARD_ID,
359           .proto  = UMASS_PROTO_SCSI | UMASS_PROTO_BBB,
360           .quirks = FORCE_SHORT_INQUIRY | NO_START_STOP | IGNORE_RESIDUE
361         },
362         /* Microtech USB CameraMate */
363         { .vendor = 0x07af, .product = 0x0006, .release = WILDCARD_ID,
364           .proto  = UMASS_PROTO_SCSI | UMASS_PROTO_CBI,
365           .quirks = NO_TEST_UNIT_READY | NO_START_STOP
366         },
367         /* M-Systems DiskOnKey */
368         { .vendor = 0x08ec, .product = 0x0010, .release = WILDCARD_ID,
369           .proto  = UMASS_PROTO_SCSI | UMASS_PROTO_BBB,
370           .quirks = IGNORE_RESIDUE | NO_GETMAXLUN | RS_NO_CLEAR_UA
371         },
372         /* M-Systems DiskOnKey */
373         { .vendor = 0x08ec, .product = 0x0011, .release = WILDCARD_ID,
374           .proto  = UMASS_PROTO_ATAPI | UMASS_PROTO_BBB,
375           .quirks = NO_QUIRKS
376         },
377         /* Olympus C-1 Digital Camera */
378         { .vendor = 0x07b4, .product = 0x0102, .release = WILDCARD_ID,
379           .proto  = UMASS_PROTO_SCSI | UMASS_PROTO_BBB,
380           .quirks = WRONG_CSWSIG
381         },
382         /* Panasonic CD-R Drive KXL-CB20AN */
383         { .vendor = 0x04da, .product = 0x0d0a, .release = WILDCARD_ID,
384           .proto  = UMASS_PROTO_SCSI | UMASS_PROTO_BBB,
385           .quirks = NO_QUIRKS
386         },
387         /* Panasonic DVD-ROM & CD-R/RW */
388         { .vendor = 0x04da, .product = 0x0d0e, .release = WILDCARD_ID,
389           .proto  = UMASS_PROTO_SCSI | UMASS_PROTO_BBB,
390           .quirks = NO_QUIRKS
391         },
392         /* Pen USB 2.0 Flash Drive */
393         { .vendor = 0x0d7d, .product = 0x1300, .release = WILDCARD_ID,
394           .proto  = UMASS_PROTO_SCSI | UMASS_PROTO_BBB,
395           .quirks = IGNORE_RESIDUE
396         },
397         /* ScanLogic SL11R-IDE */
398         { .vendor = 0x04ce, .product = 0x0002, .release = WILDCARD_ID,
399           .proto  = UMASS_PROTO_ATAPI | UMASS_PROTO_CBI_I,
400           .quirks = NO_QUIRKS
401         },
402         /* Shuttle Technology E-USB Bridge */
403         { .vendor = 0x04e6, .product = 0x0001, .release = WILDCARD_ID,
404           .proto  = UMASS_PROTO_ATAPI | UMASS_PROTO_CBI_I,
405           .quirks = NO_TEST_UNIT_READY | NO_START_STOP | SHUTTLE_INIT
406         },
407         /* Sigmatel i-Bead 100 MP3 Player */
408         { .vendor = 0x066f, .product = 0x8008, .release = WILDCARD_ID,
409           .proto  = UMASS_PROTO_SCSI | UMASS_PROTO_BBB,
410           .quirks = SHUTTLE_INIT
411         },
412         /* Sony DSC cameras */
413         { .vendor = 0x054c, .product = 0x0010, .release = WILDCARD_ID,
414           .proto  = UMASS_PROTO_RBC | UMASS_PROTO_CBI,
415           .quirks = NO_QUIRKS
416         },
417         /* Sony MSC memory stick slot */
418         { .vendor = 0x054c, .product = 0x0032, .release = WILDCARD_ID,
419           .proto  = UMASS_PROTO_RBC | UMASS_PROTO_CBI,
420           .quirks = NO_QUIRKS
421         },
422         /* Trek Technology ThumbDrive 8MB */
423         { .vendor = 0x0a16, .product = 0x9988, .release = WILDCARD_ID,
424           .proto  = UMASS_PROTO_ATAPI | UMASS_PROTO_BBB,
425           .quirks = IGNORE_RESIDUE
426         },
427         /* Yano U640MO-03 */
428         { .vendor = 0x094f, .product = 0x0101, .release = WILDCARD_ID,
429           .proto  = UMASS_PROTO_ATAPI | UMASS_PROTO_CBI_I,
430           .quirks = FORCE_SHORT_INQUIRY
431         },
432         { .vendor = EOT_ID, .product = EOT_ID, .release = EOT_ID,
433           .proto  = 0, .quirks = 0 }
434 };
435
436
437 /* the per device structure */
438 struct umass_softc {
439         device_t                sc_dev;         /* base device */
440         usbd_device_handle      sc_udev;        /* USB device */
441
442         struct cam_sim          *umass_sim;     /* SCSI Interface Module */
443
444         unsigned char           flags;          /* various device flags */
445 #       define UMASS_FLAGS_GONE         0x01    /* devices is no more */
446
447         u_int16_t               proto;          /* wire and cmd protocol */
448         u_int16_t               quirks;         /* they got it almost right */
449
450         usbd_interface_handle   iface;          /* Mass Storage interface */
451         int                     ifaceno;        /* MS iface number */
452
453         u_int8_t                bulkin;         /* bulk-in Endpoint Address */
454         u_int8_t                bulkout;        /* bulk-out Endpoint Address */
455         u_int8_t                intrin;         /* intr-in Endp. (CBI) */
456         usbd_pipe_handle        bulkin_pipe;
457         usbd_pipe_handle        bulkout_pipe;
458         usbd_pipe_handle        intrin_pipe;
459
460         /* Reset the device in a wire protocol specific way */
461         wire_reset_f            reset;
462
463         /* The start of a wire transfer. It prepares the whole transfer (cmd,
464          * data, and status stage) and initiates it. It is up to the state
465          * machine (below) to handle the various stages and errors in these
466          */
467         wire_transfer_f         transfer;
468
469         /* The state machine, handling the various states during a transfer */
470         wire_state_f            state;
471
472         /* The command transform function is used to conver the SCSI commands
473          * into their derivatives, like UFI, ATAPI, and friends.
474          */
475         command_transform_f     transform;      /* command transform */
476
477         /* Bulk specific variables for transfers in progress */
478         umass_bbb_cbw_t         cbw;    /* command block wrapper */
479         umass_bbb_csw_t         csw;    /* command status wrapper*/
480         /* CBI specific variables for transfers in progress */
481         umass_cbi_cbl_t         cbl;    /* command block */
482         umass_cbi_sbl_t         sbl;    /* status block */
483
484         /* generic variables for transfers in progress */
485         /* ctrl transfer requests */
486         usb_device_request_t    request;
487
488         /* xfer handles
489          * Most of our operations are initiated from interrupt context, so
490          * we need to avoid using the one that is in use. We want to avoid
491          * allocating them in the interrupt context as well.
492          */
493         /* indices into array below */
494 #       define XFER_BBB_CBW             0       /* Bulk-Only */
495 #       define XFER_BBB_DATA            1
496 #       define XFER_BBB_DCLEAR          2
497 #       define XFER_BBB_CSW1            3
498 #       define XFER_BBB_CSW2            4
499 #       define XFER_BBB_SCLEAR          5
500 #       define XFER_BBB_RESET1          6
501 #       define XFER_BBB_RESET2          7
502 #       define XFER_BBB_RESET3          8
503
504 #       define XFER_CBI_CB              0       /* CBI */
505 #       define XFER_CBI_DATA            1
506 #       define XFER_CBI_STATUS          2
507 #       define XFER_CBI_DCLEAR          3
508 #       define XFER_CBI_SCLEAR          4
509 #       define XFER_CBI_RESET1          5
510 #       define XFER_CBI_RESET2          6
511 #       define XFER_CBI_RESET3          7
512
513 #       define XFER_NR                  9       /* maximum number */
514
515         usbd_xfer_handle        transfer_xfer[XFER_NR]; /* for ctrl xfers */
516
517         int                     transfer_dir;           /* data direction */
518         void                    *transfer_data;         /* data buffer */
519         int                     transfer_datalen;       /* (maximum) length */
520         int                     transfer_actlen;        /* actual length */
521         transfer_cb_f           transfer_cb;            /* callback */
522         void                    *transfer_priv;         /* for callback */
523         int                     transfer_status;
524
525         int                     transfer_state;
526 #       define TSTATE_ATTACH                    0       /* in attach */
527 #       define TSTATE_IDLE                      1
528 #       define TSTATE_BBB_COMMAND               2       /* CBW transfer */
529 #       define TSTATE_BBB_DATA                  3       /* Data transfer */
530 #       define TSTATE_BBB_DCLEAR                4       /* clear endpt stall */
531 #       define TSTATE_BBB_STATUS1               5       /* clear endpt stall */
532 #       define TSTATE_BBB_SCLEAR                6       /* clear endpt stall */
533 #       define TSTATE_BBB_STATUS2               7       /* CSW transfer */
534 #       define TSTATE_BBB_RESET1                8       /* reset command */
535 #       define TSTATE_BBB_RESET2                9       /* in clear stall */
536 #       define TSTATE_BBB_RESET3                10      /* out clear stall */
537 #       define TSTATE_CBI_COMMAND               11      /* command transfer */
538 #       define TSTATE_CBI_DATA                  12      /* data transfer */
539 #       define TSTATE_CBI_STATUS                13      /* status transfer */
540 #       define TSTATE_CBI_DCLEAR                14      /* clear ep stall */
541 #       define TSTATE_CBI_SCLEAR                15      /* clear ep stall */
542 #       define TSTATE_CBI_RESET1                16      /* reset command */
543 #       define TSTATE_CBI_RESET2                17      /* in clear stall */
544 #       define TSTATE_CBI_RESET3                18      /* out clear stall */
545 #       define TSTATE_STATES                    19      /* # of states above */
546
547
548         /* SCSI/CAM specific variables */
549         unsigned char           cam_scsi_command[CAM_MAX_CDBLEN];
550         unsigned char           cam_scsi_command2[CAM_MAX_CDBLEN];
551         struct scsi_sense       cam_scsi_sense;
552         struct scsi_sense       cam_scsi_test_unit_ready;
553
554         int                     maxlun;                 /* maximum LUN number */
555         struct callout          rescan_timeout;
556 };
557
558 #ifdef USB_DEBUG
559 char *states[TSTATE_STATES+1] = {
560         /* should be kept in sync with the list at transfer_state */
561         "Attach",
562         "Idle",
563         "BBB CBW",
564         "BBB Data",
565         "BBB Data bulk-in/-out clear stall",
566         "BBB CSW, 1st attempt",
567         "BBB CSW bulk-in clear stall",
568         "BBB CSW, 2nd attempt",
569         "BBB Reset",
570         "BBB bulk-in clear stall",
571         "BBB bulk-out clear stall",
572         "CBI Command",
573         "CBI Data",
574         "CBI Status",
575         "CBI Data bulk-in/-out clear stall",
576         "CBI Status intr-in clear stall",
577         "CBI Reset",
578         "CBI bulk-in clear stall",
579         "CBI bulk-out clear stall",
580         NULL
581 };
582 #endif
583
584 /* If device cannot return valid inquiry data, fake it */
585 static uint8_t fake_inq_data[SHORT_INQUIRY_LENGTH] = {
586         0, /*removable*/ 0x80, SCSI_REV_2, SCSI_REV_2,
587         /*additional_length*/ 31, 0, 0, 0
588 };
589
590 /* USB device probe/attach/detach functions */
591 static device_probe_t umass_match;
592 static device_attach_t umass_attach;
593 static device_detach_t umass_detach;
594
595 static devclass_t umass_devclass;
596
597 static kobj_method_t umass_methods[] = {
598         DEVMETHOD(device_probe, umass_match),
599         DEVMETHOD(device_attach, umass_attach),
600         DEVMETHOD(device_detach, umass_detach),
601         {0,0},
602         {0,0}
603 };
604
605 static driver_t umass_driver = {
606         "umass",
607         umass_methods,
608         sizeof(struct umass_softc)
609 };
610
611 MODULE_DEPEND(umass, usb, 1, 1, 1);
612
613 static int umass_match_proto    (struct umass_softc *sc,
614                                 usbd_interface_handle iface,
615                                 usbd_device_handle udev);
616
617 /* quirk functions */
618 static void umass_init_shuttle  (struct umass_softc *sc);
619
620 /* generic transfer functions */
621 static usbd_status umass_setup_transfer (struct umass_softc *sc,
622                                 usbd_pipe_handle pipe,
623                                 void *buffer, int buflen, int flags,
624                                 usbd_xfer_handle xfer);
625 static usbd_status umass_setup_ctrl_transfer    (struct umass_softc *sc,
626                                 usbd_device_handle udev,
627                                 usb_device_request_t *req,
628                                 void *buffer, int buflen, int flags,
629                                 usbd_xfer_handle xfer);
630 static void umass_clear_endpoint_stall  (struct umass_softc *sc,
631                                 u_int8_t endpt, usbd_pipe_handle pipe,
632                                 int state, usbd_xfer_handle xfer);
633 static void umass_reset         (struct umass_softc *sc,
634                                 transfer_cb_f cb, void *priv);
635
636 /* Bulk-Only related functions */
637 static void umass_bbb_reset     (struct umass_softc *sc, int status);
638 static void umass_bbb_transfer  (struct umass_softc *sc, int lun,
639                                 void *cmd, int cmdlen,
640                                 void *data, int datalen, int dir,
641                                 transfer_cb_f cb, void *priv);
642 static void umass_bbb_state     (usbd_xfer_handle xfer,
643                                 usbd_private_handle priv,
644                                 usbd_status err);
645 static int umass_bbb_get_max_lun
646                                 (struct umass_softc *sc);
647
648 /* CBI related functions */
649 static int umass_cbi_adsc       (struct umass_softc *sc,
650                                 char *buffer, int buflen,
651                                 usbd_xfer_handle xfer);
652 static void umass_cbi_reset     (struct umass_softc *sc, int status);
653 static void umass_cbi_transfer  (struct umass_softc *sc, int lun,
654                                 void *cmd, int cmdlen,
655                                 void *data, int datalen, int dir,
656                                 transfer_cb_f cb, void *priv);
657 static void umass_cbi_state     (usbd_xfer_handle xfer,
658                                 usbd_private_handle priv, usbd_status err);
659
660 /* CAM related functions */
661 static void umass_cam_action    (struct cam_sim *sim, union ccb *ccb);
662 static void umass_cam_poll      (struct cam_sim *sim);
663
664 static void umass_cam_cb        (struct umass_softc *sc, void *priv,
665                                 int residue, int status);
666 static void umass_cam_sense_cb  (struct umass_softc *sc, void *priv,
667                                 int residue, int status);
668 static void umass_cam_quirk_cb  (struct umass_softc *sc, void *priv,
669                                 int residue, int status);
670
671 static void umass_cam_rescan_callback
672                                 (struct cam_periph *periph,union ccb *ccb);
673 static void umass_cam_rescan    (void *addr);
674
675 static int umass_cam_attach_sim (struct umass_softc *sc);
676 static int umass_cam_attach     (struct umass_softc *sc);
677 static int umass_cam_detach_sim (struct umass_softc *sc);
678
679
680 /* SCSI specific functions */
681 static int umass_scsi_transform (struct umass_softc *sc,
682                                 unsigned char *cmd, int cmdlen,
683                                 unsigned char **rcmd, int *rcmdlen);
684
685 /* UFI specific functions */
686 #define UFI_COMMAND_LENGTH      12      /* UFI commands are always 12 bytes */
687 static int umass_ufi_transform  (struct umass_softc *sc,
688                                 unsigned char *cmd, int cmdlen,
689                                 unsigned char **rcmd, int *rcmdlen);
690
691 /* ATAPI (8070i) specific functions */
692 #define ATAPI_COMMAND_LENGTH    12      /* ATAPI commands are always 12 bytes */
693 static int umass_atapi_transform        (struct umass_softc *sc,
694                                 unsigned char *cmd, int cmdlen,
695                                 unsigned char **rcmd, int *rcmdlen);
696
697 /* RBC specific functions */
698 static int umass_rbc_transform  (struct umass_softc *sc,
699                                 unsigned char *cmd, int cmdlen,
700                                 unsigned char **rcmd, int *rcmdlen);
701
702 #ifdef USB_DEBUG
703 /* General debugging functions */
704 static void umass_bbb_dump_cbw  (struct umass_softc *sc, umass_bbb_cbw_t *cbw);
705 static void umass_bbb_dump_csw  (struct umass_softc *sc, umass_bbb_csw_t *csw);
706 static void umass_cbi_dump_cmd  (struct umass_softc *sc, void *cmd, int cmdlen);
707 static void umass_dump_buffer   (struct umass_softc *sc, u_int8_t *buffer,
708                                 int buflen, int printlen);
709 #endif
710
711 MODULE_DEPEND(umass, cam, 1,1,1);
712
713 /*
714  * USB device probe/attach/detach
715  */
716
717 /*
718  * Match the device we are seeing with the devices supported. Fill in the
719  * description in the softc accordingly. This function is called from both
720  * probe and attach.
721  */
722
723 static int
724 umass_match_proto(struct umass_softc *sc, usbd_interface_handle iface,
725                   usbd_device_handle udev)
726 {
727         usb_device_descriptor_t *dd;
728         usb_interface_descriptor_t *id;
729         int i;
730         int found = 0;
731
732         sc->sc_udev = udev;
733         sc->proto = 0;
734         sc->quirks = 0;
735
736         dd = usbd_get_device_descriptor(udev);
737
738         /* An entry specifically for Y-E Data devices as they don't fit in the
739          * device description table.
740          */
741         if (UGETW(dd->idVendor) == 0x057b && UGETW(dd->idProduct) == 0x0000) {
742
743                 /* Revisions < 1.28 do not handle the inerrupt endpoint
744                  * very well.
745                  */
746                 if (UGETW(dd->bcdDevice) < 0x128) {
747                         sc->proto = UMASS_PROTO_UFI | UMASS_PROTO_CBI;
748                 } else {
749                         sc->proto = UMASS_PROTO_UFI | UMASS_PROTO_CBI_I;
750                 }
751
752                 /*
753                  * Revisions < 1.28 do not have the TEST UNIT READY command
754                  * Revisions == 1.28 have a broken TEST UNIT READY
755                  */
756                 if (UGETW(dd->bcdDevice) <= 0x128)
757                         sc->quirks |= NO_TEST_UNIT_READY;
758
759                 sc->quirks |= RS_NO_CLEAR_UA | FLOPPY_SPEED;
760                 return(UMATCH_VENDOR_PRODUCT);
761         }
762
763         /* Check the list of supported devices for a match. While looking,
764          * check for wildcarded and fully matched. First match wins.
765          */
766         for (i = 0; umass_devdescrs[i].vendor != EOT_ID && !found; i++) {
767                 if (umass_devdescrs[i].vendor == WILDCARD_ID &&
768                     umass_devdescrs[i].product == WILDCARD_ID &&
769                     umass_devdescrs[i].release == WILDCARD_ID) {
770                         kprintf("umass: ignoring invalid wildcard quirk\n");
771                         continue;
772                 }
773                 if ((umass_devdescrs[i].vendor == UGETW(dd->idVendor) ||
774                      umass_devdescrs[i].vendor == WILDCARD_ID)
775                  && (umass_devdescrs[i].product == UGETW(dd->idProduct) ||
776                      umass_devdescrs[i].product == WILDCARD_ID)) {
777                         if (umass_devdescrs[i].release == WILDCARD_ID) {
778                                 sc->proto = umass_devdescrs[i].proto;
779                                 sc->quirks = umass_devdescrs[i].quirks;
780                                 return (UMATCH_VENDOR_PRODUCT);
781                         } else if (umass_devdescrs[i].release ==
782                             UGETW(dd->bcdDevice)) {
783                                 sc->proto = umass_devdescrs[i].proto;
784                                 sc->quirks = umass_devdescrs[i].quirks;
785                                 return (UMATCH_VENDOR_PRODUCT_REV);
786                         } /* else RID does not match */
787                 }
788         }
789
790         /* Check for a standards compliant device */
791
792         id = usbd_get_interface_descriptor(iface);
793         if (id == NULL || id->bInterfaceClass != UICLASS_MASS)
794                 return(UMATCH_NONE);
795         
796         switch (id->bInterfaceSubClass) {
797         case UISUBCLASS_SCSI:
798                 sc->proto |= UMASS_PROTO_SCSI;
799                 break;
800         case UISUBCLASS_UFI:
801                 sc->proto |= UMASS_PROTO_UFI;
802                 break;
803         case UISUBCLASS_RBC:
804                 sc->proto |= UMASS_PROTO_RBC;
805                 break;
806         case UISUBCLASS_SFF8020I:
807         case UISUBCLASS_SFF8070I:
808                 sc->proto |= UMASS_PROTO_ATAPI;
809                 break;
810         default:
811                 DPRINTF(UDMASS_GEN, ("%s: Unsupported command protocol %d\n",
812                         device_get_nameunit(sc->sc_dev), id->bInterfaceSubClass));
813                 return(UMATCH_NONE);
814         }
815
816         switch (id->bInterfaceProtocol) {
817         case UIPROTO_MASS_CBI:
818                 sc->proto |= UMASS_PROTO_CBI;
819                 break;
820         case UIPROTO_MASS_CBI_I:
821                 sc->proto |= UMASS_PROTO_CBI_I;
822                 break;
823         case UIPROTO_MASS_BBB_OLD:
824         case UIPROTO_MASS_BBB:
825                 sc->proto |= UMASS_PROTO_BBB;
826                 break;
827         default:
828                 DPRINTF(UDMASS_GEN, ("%s: Unsupported wire protocol %d\n",
829                         device_get_nameunit(sc->sc_dev), id->bInterfaceProtocol));
830                 return(UMATCH_NONE);
831         }
832
833         return(UMATCH_DEVCLASS_DEVSUBCLASS_DEVPROTO);
834 }
835
836 static int
837 umass_match(device_t self)
838 {
839         struct usb_attach_arg *uaa = device_get_ivars(self);
840         struct umass_softc *sc = device_get_softc(self);
841
842         sc->sc_dev = self;
843
844         if (uaa->iface == NULL)
845                 return(UMATCH_NONE);
846
847         return(umass_match_proto(sc, uaa->iface, uaa->device));
848 }
849
850 static int
851 umass_attach(device_t self)
852 {
853         struct umass_softc *sc = device_get_softc(self);
854         struct usb_attach_arg *uaa = device_get_ivars(self);
855         usb_interface_descriptor_t *id;
856         usb_endpoint_descriptor_t *ed;
857         char devinfo[1024];
858         int i;
859         int err;
860
861         /*
862          * the softc struct is bzero-ed in device_set_driver. We can safely
863          * call umass_detach without specifically initialising the struct.
864          */
865
866         usbd_devinfo(uaa->device, 0, devinfo);
867         sc->sc_dev = self;
868         device_set_desc_copy(self, devinfo);
869
870         sc->iface = uaa->iface;
871         sc->ifaceno = uaa->ifaceno;
872
873         /* initialise the proto and drive values in the umass_softc (again) */
874         (void) umass_match_proto(sc, sc->iface, uaa->device);
875
876         id = usbd_get_interface_descriptor(sc->iface);
877         kprintf("%s: %s\n", device_get_nameunit(sc->sc_dev), devinfo);
878 #ifdef USB_DEBUG
879         kprintf("%s: ", device_get_nameunit(sc->sc_dev));
880         switch (sc->proto&UMASS_PROTO_COMMAND) {
881         case UMASS_PROTO_SCSI:
882                 kprintf("SCSI");
883                 break;
884         case UMASS_PROTO_ATAPI:
885                 kprintf("8070i (ATAPI)");
886                 break;
887         case UMASS_PROTO_UFI:
888                 kprintf("UFI");
889                 break;
890         case UMASS_PROTO_RBC:
891                 kprintf("RBC");
892                 break;
893         default:
894                 kprintf("(unknown 0x%02x)", sc->proto&UMASS_PROTO_COMMAND);
895                 break;
896         }
897         kprintf(" over ");
898         switch (sc->proto&UMASS_PROTO_WIRE) {
899         case UMASS_PROTO_BBB:
900                 kprintf("Bulk-Only");
901                 break;
902         case UMASS_PROTO_CBI:                   /* uses Comand/Bulk pipes */
903                 kprintf("CBI");
904                 break;
905         case UMASS_PROTO_CBI_I:         /* uses Comand/Bulk/Interrupt pipes */
906                 kprintf("CBI with CCI");
907 #ifndef CBI_I
908                 kprintf(" (using CBI)");
909 #endif
910                 break;
911         default:
912                 kprintf("(unknown 0x%02x)", sc->proto&UMASS_PROTO_WIRE);
913         }
914         kprintf("; quirks = 0x%04x\n", sc->quirks);
915 #endif
916
917 #ifndef CBI_I
918         if (sc->proto & UMASS_PROTO_CBI_I) {
919                 /* See beginning of file for comment on the use of CBI with CCI */
920                 sc->proto = (sc->proto & ~UMASS_PROTO_CBI_I) | UMASS_PROTO_CBI;
921         }
922 #endif
923
924         if (sc->quirks & ALT_IFACE_1) {
925                 err = usbd_set_interface(0, 1);
926                 if (err) {
927                         DPRINTF(UDMASS_USB, ("%s: could not switch to "
928                                 "Alt Interface %d\n",
929                                 device_get_nameunit(sc->sc_dev), 1));
930                         umass_detach(self);
931                         return ENXIO;
932                 }
933         }
934
935         /*
936          * In addition to the Control endpoint the following endpoints
937          * are required:
938          * a) bulk-in endpoint.
939          * b) bulk-out endpoint.
940          * and for Control/Bulk/Interrupt with CCI (CBI_I)
941          * c) intr-in
942          *
943          * The endpoint addresses are not fixed, so we have to read them
944          * from the device descriptors of the current interface.
945          */
946         for (i = 0 ; i < id->bNumEndpoints ; i++) {
947                 ed = usbd_interface2endpoint_descriptor(sc->iface, i);
948                 if (!ed) {
949                         kprintf("%s: could not read endpoint descriptor\n",
950                                device_get_nameunit(sc->sc_dev));
951                         return ENXIO;
952                 }
953                 if (UE_GET_DIR(ed->bEndpointAddress) == UE_DIR_IN
954                     && (ed->bmAttributes & UE_XFERTYPE) == UE_BULK) {
955                         sc->bulkin = ed->bEndpointAddress;
956                 } else if (UE_GET_DIR(ed->bEndpointAddress) == UE_DIR_OUT
957                     && (ed->bmAttributes & UE_XFERTYPE) == UE_BULK) {
958                         sc->bulkout = ed->bEndpointAddress;
959                 } else if (sc->proto & UMASS_PROTO_CBI_I
960                     && UE_GET_DIR(ed->bEndpointAddress) == UE_DIR_IN
961                     && (ed->bmAttributes & UE_XFERTYPE) == UE_INTERRUPT) {
962                         sc->intrin = ed->bEndpointAddress;
963 #ifdef USB_DEBUG
964                         if (UGETW(ed->wMaxPacketSize) > 2) {
965                                 DPRINTF(UDMASS_CBI, ("%s: intr size is %d\n",
966                                         device_get_nameunit(sc->sc_dev),
967                                         UGETW(ed->wMaxPacketSize)));
968                         }
969 #endif
970                 }
971         }
972
973         /* check whether we found all the endpoints we need */
974         if (!sc->bulkin || !sc->bulkout
975             || (sc->proto & UMASS_PROTO_CBI_I && !sc->intrin) ) {
976                 DPRINTF(UDMASS_USB, ("%s: endpoint not found %d/%d/%d\n",
977                         device_get_nameunit(sc->sc_dev),
978                         sc->bulkin, sc->bulkout, sc->intrin));
979                 umass_detach(self);
980                 return ENXIO;
981         }
982
983         /* Open the bulk-in and -out pipe */
984         err = usbd_open_pipe(sc->iface, sc->bulkout,
985                                 USBD_EXCLUSIVE_USE, &sc->bulkout_pipe);
986         if (err) {
987                 DPRINTF(UDMASS_USB, ("%s: cannot open %d-out pipe (bulk)\n",
988                         device_get_nameunit(sc->sc_dev), sc->bulkout));
989                 umass_detach(self);
990                 return ENXIO;
991         }
992         err = usbd_open_pipe(sc->iface, sc->bulkin,
993                                 USBD_EXCLUSIVE_USE, &sc->bulkin_pipe);
994         if (err) {
995                 DPRINTF(UDMASS_USB, ("%s: could not open %d-in pipe (bulk)\n",
996                         device_get_nameunit(sc->sc_dev), sc->bulkin));
997                 umass_detach(self);
998                 return ENXIO;
999         }
1000         /* Open the intr-in pipe if the protocol is CBI with CCI.
1001          * Note: early versions of the Zip drive do have an interrupt pipe, but
1002          * this pipe is unused
1003          *
1004          * We do not open the interrupt pipe as an interrupt pipe, but as a
1005          * normal bulk endpoint. We send an IN transfer down the wire at the
1006          * appropriate time, because we know exactly when to expect data on
1007          * that endpoint. This saves bandwidth, but more important, makes the
1008          * code for handling the data on that endpoint simpler. No data
1009          * arriving concurently.
1010          */
1011         if (sc->proto & UMASS_PROTO_CBI_I) {
1012                 err = usbd_open_pipe(sc->iface, sc->intrin,
1013                                 USBD_EXCLUSIVE_USE, &sc->intrin_pipe);
1014                 if (err) {
1015                         DPRINTF(UDMASS_USB, ("%s: couldn't open %d-in (intr)\n",
1016                                 device_get_nameunit(sc->sc_dev), sc->intrin));
1017                         umass_detach(self);
1018                         return ENXIO;
1019                 }
1020         }
1021
1022         /* initialisation of generic part */
1023         sc->transfer_state = TSTATE_ATTACH;
1024
1025         /* request a sufficient number of xfer handles */
1026         for (i = 0; i < XFER_NR; i++) {
1027                 sc->transfer_xfer[i] = usbd_alloc_xfer(uaa->device);
1028                 if (!sc->transfer_xfer[i]) {
1029                         DPRINTF(UDMASS_USB, ("%s: Out of memory\n",
1030                                 device_get_nameunit(sc->sc_dev)));
1031                         umass_detach(self);
1032                         return ENXIO;
1033                 }
1034         }
1035
1036         /* Initialise the wire protocol specific methods */
1037         if (sc->proto & UMASS_PROTO_BBB) {
1038                 sc->reset = umass_bbb_reset;
1039                 sc->transfer = umass_bbb_transfer;
1040                 sc->state = umass_bbb_state;
1041         } else if (sc->proto & (UMASS_PROTO_CBI|UMASS_PROTO_CBI_I)) {
1042                 sc->reset = umass_cbi_reset;
1043                 sc->transfer = umass_cbi_transfer;
1044                 sc->state = umass_cbi_state;
1045 #ifdef USB_DEBUG
1046         } else {
1047                 panic("%s:%d: Unknown proto 0x%02x",
1048                       __FILE__, __LINE__, sc->proto);
1049 #endif
1050         }
1051
1052         if (sc->proto & UMASS_PROTO_SCSI)
1053                 sc->transform = umass_scsi_transform;
1054         else if (sc->proto & UMASS_PROTO_UFI)
1055                 sc->transform = umass_ufi_transform;
1056         else if (sc->proto & UMASS_PROTO_ATAPI)
1057                 sc->transform = umass_atapi_transform;
1058         else if (sc->proto & UMASS_PROTO_RBC)
1059                 sc->transform = umass_rbc_transform;
1060 #ifdef USB_DEBUG
1061         else
1062                 panic("No transformation defined for command proto 0x%02x",
1063                       sc->proto & UMASS_PROTO_COMMAND);
1064 #endif
1065
1066         /* From here onwards the device can be used. */
1067
1068         if (sc->quirks & SHUTTLE_INIT)
1069                 umass_init_shuttle(sc);
1070
1071         /* Get the maximum LUN supported by the device.
1072          */
1073         if ((sc->proto & UMASS_PROTO_WIRE) == UMASS_PROTO_BBB)
1074                 sc->maxlun = umass_bbb_get_max_lun(sc);
1075         else
1076                 sc->maxlun = 0;
1077
1078         if ((sc->proto & UMASS_PROTO_SCSI) ||
1079             (sc->proto & UMASS_PROTO_ATAPI) ||
1080             (sc->proto & UMASS_PROTO_UFI) ||
1081             (sc->proto & UMASS_PROTO_RBC)) {
1082                 /* Prepare the SCSI command block */
1083                 sc->cam_scsi_sense.opcode = REQUEST_SENSE;
1084                 sc->cam_scsi_test_unit_ready.opcode = TEST_UNIT_READY;
1085
1086                 /* register the SIM */
1087                 err = umass_cam_attach_sim(sc);
1088                 if (err) {
1089                         umass_detach(self);
1090                         return ENXIO;
1091                 }
1092                 /* scan the new sim */
1093                 err = umass_cam_attach(sc);
1094                 if (err) {
1095                         umass_cam_detach_sim(sc);
1096                         umass_detach(self);
1097                         return ENXIO;
1098                 }
1099         } else {
1100                 panic("%s:%d: Unknown proto 0x%02x",
1101                       __FILE__, __LINE__, sc->proto);
1102         }
1103
1104         sc->transfer_state = TSTATE_IDLE;
1105         DPRINTF(UDMASS_GEN, ("%s: Attach finished\n", device_get_nameunit(sc->sc_dev)));
1106
1107         return 0;
1108 }
1109
1110 static int
1111 umass_detach(device_t self)
1112 {
1113         struct umass_softc *sc = device_get_softc(self);
1114         int err = 0;
1115         int i;
1116         int to;
1117
1118         DPRINTF(UDMASS_USB, ("%s: detached\n", device_get_nameunit(sc->sc_dev)));
1119
1120         /*
1121          * Set UMASS_FLAGS_GONE to prevent any new transfers from being
1122          * queued, and abort any transfers in progress to ensure that
1123          * pending requests (e.g. from CAM's bus scan) are terminated.
1124          */
1125         sc->flags |= UMASS_FLAGS_GONE;
1126
1127         if (sc->bulkout_pipe)
1128                 usbd_abort_pipe(sc->bulkout_pipe);
1129         if (sc->bulkin_pipe)
1130                 usbd_abort_pipe(sc->bulkin_pipe);
1131         if (sc->intrin_pipe)
1132                 usbd_abort_pipe(sc->intrin_pipe);
1133
1134         /*
1135          * Wait until we go idle to make sure that all of our xfer requests
1136          * have finished.  We could be in the middle of a BBB reset (which
1137          * would not be effected by the pipe aborts above).
1138          */
1139         to = hz;
1140         while (sc->transfer_state != TSTATE_IDLE) {
1141                 kprintf("%s: state %d waiting for idle\n",
1142                     device_get_nameunit(sc->sc_dev), sc->transfer_state);
1143                 tsleep(sc, 0, "umassidl", to);
1144                 if (to >= hz * 10) {
1145                         kprintf("%s: state %d giving up!\n",
1146                             device_get_nameunit(sc->sc_dev), sc->transfer_state);
1147                         break;
1148                 }
1149                 to += hz;
1150         }
1151
1152         if ((sc->proto & UMASS_PROTO_SCSI) ||
1153             (sc->proto & UMASS_PROTO_ATAPI) ||
1154             (sc->proto & UMASS_PROTO_UFI) ||
1155             (sc->proto & UMASS_PROTO_RBC)) {
1156                 /* detach the SCSI host controller (SIM) */
1157                 err = umass_cam_detach_sim(sc);
1158         }
1159
1160         for (i = 0; i < XFER_NR; i++) {
1161                 if (sc->transfer_xfer[i])
1162                         usbd_free_xfer(sc->transfer_xfer[i]);
1163         }
1164
1165         /* remove all the pipes */
1166         if (sc->bulkout_pipe)
1167                 usbd_close_pipe(sc->bulkout_pipe);
1168         if (sc->bulkin_pipe)
1169                 usbd_close_pipe(sc->bulkin_pipe);
1170         if (sc->intrin_pipe)
1171                 usbd_close_pipe(sc->intrin_pipe);
1172
1173         return(err);
1174 }
1175
1176 static void
1177 umass_init_shuttle(struct umass_softc *sc)
1178 {
1179         usb_device_request_t req;
1180         u_char status[2];
1181
1182         /* The Linux driver does this, but no one can tell us what the
1183          * command does.
1184          */
1185         req.bmRequestType = UT_READ_VENDOR_DEVICE;
1186         req.bRequest = 1;       /* XXX unknown command */
1187         USETW(req.wValue, 0);
1188         USETW(req.wIndex, sc->ifaceno);
1189         USETW(req.wLength, sizeof status);
1190         (void) usbd_do_request(sc->sc_udev, &req, &status);
1191
1192         DPRINTF(UDMASS_GEN, ("%s: Shuttle init returned 0x%02x%02x\n",
1193                 device_get_nameunit(sc->sc_dev), status[0], status[1]));
1194 }
1195
1196  /*
1197  * Generic functions to handle transfers
1198  */
1199
1200 static usbd_status
1201 umass_setup_transfer(struct umass_softc *sc, usbd_pipe_handle pipe,
1202                         void *buffer, int buflen, int flags,
1203                         usbd_xfer_handle xfer)
1204 {
1205         usbd_status err;
1206
1207         /* Initialiase a USB transfer and then schedule it */
1208
1209         (void) usbd_setup_xfer(xfer, pipe, (void *) sc, buffer, buflen, flags,
1210                         UMASS_TIMEOUT, sc->state);
1211
1212         err = usbd_transfer(xfer);
1213         if (err && err != USBD_IN_PROGRESS) {
1214                 DPRINTF(UDMASS_BBB, ("%s: failed to setup transfer, %s\n",
1215                         device_get_nameunit(sc->sc_dev), usbd_errstr(err)));
1216                 return(err);
1217         }
1218
1219         return (USBD_NORMAL_COMPLETION);
1220 }
1221
1222
1223 static usbd_status
1224 umass_setup_ctrl_transfer(struct umass_softc *sc, usbd_device_handle udev,
1225          usb_device_request_t *req,
1226          void *buffer, int buflen, int flags,
1227          usbd_xfer_handle xfer)
1228 {
1229         usbd_status err;
1230
1231         /* Initialiase a USB control transfer and then schedule it */
1232
1233         (void) usbd_setup_default_xfer(xfer, udev, (void *) sc,
1234                         UMASS_TIMEOUT, req, buffer, buflen, flags, sc->state);
1235
1236         err = usbd_transfer(xfer);
1237         if (err && err != USBD_IN_PROGRESS) {
1238                 DPRINTF(UDMASS_BBB, ("%s: failed to setup ctrl transfer, %s\n",
1239                          device_get_nameunit(sc->sc_dev), usbd_errstr(err)));
1240
1241                 /* do not reset, as this would make us loop */
1242                 return(err);
1243         }
1244
1245         return (USBD_NORMAL_COMPLETION);
1246 }
1247
1248 static void
1249 umass_clear_endpoint_stall(struct umass_softc *sc,
1250                                 u_int8_t endpt, usbd_pipe_handle pipe,
1251                                 int state, usbd_xfer_handle xfer)
1252 {
1253         usbd_device_handle udev;
1254
1255         DPRINTF(UDMASS_BBB, ("%s: Clear endpoint 0x%02x stall\n",
1256                 device_get_nameunit(sc->sc_dev), endpt));
1257
1258         usbd_interface2device_handle(sc->iface, &udev);
1259
1260         sc->transfer_state = state;
1261
1262         usbd_clear_endpoint_toggle(pipe);
1263
1264         sc->request.bmRequestType = UT_WRITE_ENDPOINT;
1265         sc->request.bRequest = UR_CLEAR_FEATURE;
1266         USETW(sc->request.wValue, UF_ENDPOINT_HALT);
1267         USETW(sc->request.wIndex, endpt);
1268         USETW(sc->request.wLength, 0);
1269         umass_setup_ctrl_transfer(sc, udev, &sc->request, NULL, 0, 0, xfer);
1270 }
1271
1272 static void
1273 umass_reset(struct umass_softc *sc, transfer_cb_f cb, void *priv)
1274 {
1275         sc->transfer_cb = cb;
1276         sc->transfer_priv = priv;
1277
1278         /* The reset is a forced reset, so no error (yet) */
1279         sc->reset(sc, STATUS_CMD_OK);
1280 }
1281
1282 /*
1283  * Bulk protocol specific functions
1284  */
1285
1286 static void
1287 umass_bbb_reset(struct umass_softc *sc, int status)
1288 {
1289         usbd_device_handle udev;
1290
1291         KASSERT(sc->proto & UMASS_PROTO_BBB,
1292                 ("%s: umass_bbb_reset: wrong sc->proto 0x%02x\n",
1293                         device_get_nameunit(sc->sc_dev), sc->proto));
1294
1295         /*
1296          * Reset recovery (5.3.4 in Universal Serial Bus Mass Storage Class)
1297          *
1298          * For Reset Recovery the host shall issue in the following order:
1299          * a) a Bulk-Only Mass Storage Reset
1300          * b) a Clear Feature HALT to the Bulk-In endpoint
1301          * c) a Clear Feature HALT to the Bulk-Out endpoint
1302          *
1303          * This is done in 3 steps, states:
1304          * TSTATE_BBB_RESET1
1305          * TSTATE_BBB_RESET2
1306          * TSTATE_BBB_RESET3
1307          *
1308          * If the reset doesn't succeed, the device should be port reset.
1309          */
1310
1311         DPRINTF(UDMASS_BBB, ("%s: Bulk Reset\n",
1312                 device_get_nameunit(sc->sc_dev)));
1313
1314         sc->transfer_state = TSTATE_BBB_RESET1;
1315         sc->transfer_status = status;
1316
1317         usbd_interface2device_handle(sc->iface, &udev);
1318
1319         /* reset is a class specific interface write */
1320         sc->request.bmRequestType = UT_WRITE_CLASS_INTERFACE;
1321         sc->request.bRequest = UR_BBB_RESET;
1322         USETW(sc->request.wValue, 0);
1323         USETW(sc->request.wIndex, sc->ifaceno);
1324         USETW(sc->request.wLength, 0);
1325         umass_setup_ctrl_transfer(sc, udev, &sc->request, NULL, 0, 0,
1326                                   sc->transfer_xfer[XFER_BBB_RESET1]);
1327 }
1328
1329 static void
1330 umass_bbb_transfer(struct umass_softc *sc, int lun, void *cmd, int cmdlen,
1331                     void *data, int datalen, int dir,
1332                     transfer_cb_f cb, void *priv)
1333 {
1334         KASSERT(sc->proto & UMASS_PROTO_BBB,
1335                 ("%s: umass_bbb_transfer: wrong sc->proto 0x%02x\n",
1336                         device_get_nameunit(sc->sc_dev), sc->proto));
1337
1338         /*
1339          * Do a Bulk-Only transfer with cmdlen bytes from cmd, possibly
1340          * a data phase of datalen bytes from/to the device and finally a
1341          * csw read phase.
1342          * If the data direction was inbound a maximum of datalen bytes
1343          * is stored in the buffer pointed to by data.
1344          *
1345          * umass_bbb_transfer initialises the transfer and lets the state
1346          * machine in umass_bbb_state handle the completion. It uses the
1347          * following states:
1348          * TSTATE_BBB_COMMAND
1349          *   -> TSTATE_BBB_DATA
1350          *   -> TSTATE_BBB_STATUS
1351          *   -> TSTATE_BBB_STATUS2
1352          *   -> TSTATE_BBB_IDLE
1353          *
1354          * An error in any of those states will invoke
1355          * umass_bbb_reset.
1356          */
1357
1358         /* check the given arguments */
1359         KASSERT(datalen == 0 || data != NULL,
1360                 ("%s: datalen > 0, but no buffer",device_get_nameunit(sc->sc_dev)));
1361         KASSERT(cmdlen <= CBWCDBLENGTH,
1362                 ("%s: cmdlen exceeds CDB length in CBW (%d > %d)",
1363                         device_get_nameunit(sc->sc_dev), cmdlen, CBWCDBLENGTH));
1364         KASSERT(dir == DIR_NONE || datalen > 0,
1365                 ("%s: datalen == 0 while direction is not NONE\n",
1366                         device_get_nameunit(sc->sc_dev)));
1367         KASSERT(datalen == 0 || dir != DIR_NONE,
1368                 ("%s: direction is NONE while datalen is not zero\n",
1369                         device_get_nameunit(sc->sc_dev)));
1370         KASSERT(sizeof(umass_bbb_cbw_t) == UMASS_BBB_CBW_SIZE,
1371                 ("%s: CBW struct does not have the right size (%ld vs. %d)\n",
1372                         device_get_nameunit(sc->sc_dev),
1373                         (long)sizeof(umass_bbb_cbw_t), UMASS_BBB_CBW_SIZE));
1374         KASSERT(sizeof(umass_bbb_csw_t) == UMASS_BBB_CSW_SIZE,
1375                 ("%s: CSW struct does not have the right size (%ld vs. %d)\n",
1376                         device_get_nameunit(sc->sc_dev),
1377                         (long)sizeof(umass_bbb_csw_t), UMASS_BBB_CSW_SIZE));
1378
1379         /*
1380          * Determine the direction of the data transfer and the length.
1381          *
1382          * dCBWDataTransferLength (datalen) :
1383          *   This field indicates the number of bytes of data that the host
1384          *   intends to transfer on the IN or OUT Bulk endpoint(as indicated by
1385          *   the Direction bit) during the execution of this command. If this
1386          *   field is set to 0, the device will expect that no data will be
1387          *   transferred IN or OUT during this command, regardless of the value
1388          *   of the Direction bit defined in dCBWFlags.
1389          *
1390          * dCBWFlags (dir) :
1391          *   The bits of the Flags field are defined as follows:
1392          *     Bits 0-6  reserved
1393          *     Bit  7    Direction - this bit shall be ignored if the
1394          *                           dCBWDataTransferLength field is zero.
1395          *               0 = data Out from host to device
1396          *               1 = data In from device to host
1397          */
1398
1399         /* Fill in the Command Block Wrapper
1400          * We fill in all the fields, so there is no need to bzero it first.
1401          */
1402         USETDW(sc->cbw.dCBWSignature, CBWSIGNATURE);
1403         /* We don't care about the initial value, as long as the values are unique */
1404         USETDW(sc->cbw.dCBWTag, UGETDW(sc->cbw.dCBWTag) + 1);
1405         USETDW(sc->cbw.dCBWDataTransferLength, datalen);
1406         /* DIR_NONE is treated as DIR_OUT (0x00) */
1407         sc->cbw.bCBWFlags = (dir == DIR_IN? CBWFLAGS_IN:CBWFLAGS_OUT);
1408         sc->cbw.bCBWLUN = lun;
1409         sc->cbw.bCDBLength = cmdlen;
1410         bcopy(cmd, sc->cbw.CBWCDB, cmdlen);
1411
1412         DIF(UDMASS_BBB, umass_bbb_dump_cbw(sc, &sc->cbw));
1413
1414         /* store the details for the data transfer phase */
1415         sc->transfer_dir = dir;
1416         sc->transfer_data = data;
1417         sc->transfer_datalen = datalen;
1418         sc->transfer_actlen = 0;
1419         sc->transfer_cb = cb;
1420         sc->transfer_priv = priv;
1421         sc->transfer_status = STATUS_CMD_OK;
1422
1423         /* move from idle to the command state */
1424         sc->transfer_state = TSTATE_BBB_COMMAND;
1425
1426         /* Send the CBW from host to device via bulk-out endpoint. */
1427         if (umass_setup_transfer(sc, sc->bulkout_pipe,
1428                         &sc->cbw, UMASS_BBB_CBW_SIZE, 0,
1429                         sc->transfer_xfer[XFER_BBB_CBW])) {
1430                 umass_bbb_reset(sc, STATUS_WIRE_FAILED);
1431         }
1432 }
1433
1434
1435 static void
1436 umass_bbb_state(usbd_xfer_handle xfer, usbd_private_handle priv,
1437                 usbd_status err)
1438 {
1439         struct umass_softc *sc = (struct umass_softc *) priv;
1440         usbd_xfer_handle next_xfer;
1441
1442         KASSERT(sc->proto & UMASS_PROTO_BBB,
1443                 ("%s: umass_bbb_state: wrong sc->proto 0x%02x\n",
1444                         device_get_nameunit(sc->sc_dev), sc->proto));
1445
1446         /*
1447          * State handling for BBB transfers.
1448          *
1449          * The subroutine is rather long. It steps through the states given in
1450          * Annex A of the Bulk-Only specification.
1451          * Each state first does the error handling of the previous transfer
1452          * and then prepares the next transfer.
1453          * Each transfer is done asynchroneously so after the request/transfer
1454          * has been submitted you will find a 'return;'.
1455          */
1456
1457         DPRINTF(UDMASS_BBB, ("%s: Handling BBB state %d (%s), xfer=%p, %s\n",
1458                 device_get_nameunit(sc->sc_dev), sc->transfer_state,
1459                 states[sc->transfer_state], xfer, usbd_errstr(err)));
1460
1461         switch (sc->transfer_state) {
1462
1463         /***** Bulk Transfer *****/
1464         case TSTATE_BBB_COMMAND:
1465                 /* Command transport phase, error handling */
1466                 if (err) {
1467                         DPRINTF(UDMASS_BBB, ("%s: failed to send CBW\n",
1468                                 device_get_nameunit(sc->sc_dev)));
1469                         /* If the device detects that the CBW is invalid, then
1470                          * the device may STALL both bulk endpoints and require
1471                          * a Bulk-Reset
1472                          */
1473                         umass_bbb_reset(sc, STATUS_WIRE_FAILED);
1474                         return;
1475                 }
1476
1477                 /* Data transport phase, setup transfer */
1478                 sc->transfer_state = TSTATE_BBB_DATA;
1479                 if (sc->transfer_dir == DIR_IN) {
1480                         if (umass_setup_transfer(sc, sc->bulkin_pipe,
1481                                         sc->transfer_data, sc->transfer_datalen,
1482                                         USBD_SHORT_XFER_OK,
1483                                         sc->transfer_xfer[XFER_BBB_DATA]))
1484                                 umass_bbb_reset(sc, STATUS_WIRE_FAILED);
1485
1486                         return;
1487                 } else if (sc->transfer_dir == DIR_OUT) {
1488                         if (umass_setup_transfer(sc, sc->bulkout_pipe,
1489                                         sc->transfer_data, sc->transfer_datalen,
1490                                         0,      /* fixed length transfer */
1491                                         sc->transfer_xfer[XFER_BBB_DATA]))
1492                                 umass_bbb_reset(sc, STATUS_WIRE_FAILED);
1493
1494                         return;
1495                 } else {
1496                         DPRINTF(UDMASS_BBB, ("%s: no data phase\n",
1497                                 device_get_nameunit(sc->sc_dev)));
1498                 }
1499
1500                 /* FALLTHROUGH if no data phase, err == 0 */
1501         case TSTATE_BBB_DATA:
1502                 /* Command transport phase, error handling (ignored if no data
1503                  * phase (fallthrough from previous state)) */
1504                 if (sc->transfer_dir != DIR_NONE) {
1505                         /* retrieve the length of the transfer that was done */
1506                         usbd_get_xfer_status(xfer, NULL, NULL,
1507                                                 &sc->transfer_actlen, NULL);
1508
1509                         if (err) {
1510                                 DPRINTF(UDMASS_BBB, ("%s: Data-%s %db failed, "
1511                                         "%s\n", device_get_nameunit(sc->sc_dev),
1512                                         (sc->transfer_dir == DIR_IN?"in":"out"),
1513                                         sc->transfer_datalen,usbd_errstr(err)));
1514
1515                                 if (err == USBD_STALLED) {
1516                                         umass_clear_endpoint_stall(sc,
1517                                           (sc->transfer_dir == DIR_IN?
1518                                             sc->bulkin:sc->bulkout),
1519                                           (sc->transfer_dir == DIR_IN?
1520                                             sc->bulkin_pipe:sc->bulkout_pipe),
1521                                           TSTATE_BBB_DCLEAR,
1522                                           sc->transfer_xfer[XFER_BBB_DCLEAR]);
1523                                         return;
1524                                 } else {
1525                                         /* Unless the error is a pipe stall the
1526                                          * error is fatal.
1527                                          */
1528                                         umass_bbb_reset(sc,STATUS_WIRE_FAILED);
1529                                         return;
1530                                 }
1531                         }
1532                 }
1533
1534                 DIF(UDMASS_BBB, if (sc->transfer_dir == DIR_IN)
1535                                         umass_dump_buffer(sc, sc->transfer_data,
1536                                                 sc->transfer_datalen, 48));
1537
1538
1539
1540                 /* FALLTHROUGH, err == 0 (no data phase or successfull) */
1541         case TSTATE_BBB_DCLEAR: /* stall clear after data phase */
1542         case TSTATE_BBB_SCLEAR: /* stall clear after status phase */
1543                 /* Reading of CSW after bulk stall condition in data phase
1544                  * (TSTATE_BBB_DATA2) or bulk-in stall condition after
1545                  * reading CSW (TSTATE_BBB_SCLEAR).
1546                  * In the case of no data phase or successfull data phase,
1547                  * err == 0 and the following if block is passed.
1548                  */
1549                 if (err) {      /* should not occur */
1550                         /* try the transfer below, even if clear stall failed */
1551                         DPRINTF(UDMASS_BBB, ("%s: bulk-%s stall clear failed"
1552                                 ", %s\n", device_get_nameunit(sc->sc_dev),
1553                                 (sc->transfer_dir == DIR_IN? "in":"out"),
1554                                 usbd_errstr(err)));
1555                         umass_bbb_reset(sc, STATUS_WIRE_FAILED);
1556                         return;
1557                 }
1558
1559                 /* Status transport phase, setup transfer */
1560                 if (sc->transfer_state == TSTATE_BBB_COMMAND ||
1561                     sc->transfer_state == TSTATE_BBB_DATA ||
1562                     sc->transfer_state == TSTATE_BBB_DCLEAR) {
1563                         /* After no data phase, successfull data phase and
1564                          * after clearing bulk-in/-out stall condition
1565                          */
1566                         sc->transfer_state = TSTATE_BBB_STATUS1;
1567                         next_xfer = sc->transfer_xfer[XFER_BBB_CSW1];
1568                 } else {
1569                         /* After first attempt of fetching CSW */
1570                         sc->transfer_state = TSTATE_BBB_STATUS2;
1571                         next_xfer = sc->transfer_xfer[XFER_BBB_CSW2];
1572                 }
1573
1574                 /* Read the Command Status Wrapper via bulk-in endpoint. */
1575                 if (umass_setup_transfer(sc, sc->bulkin_pipe,
1576                                 &sc->csw, UMASS_BBB_CSW_SIZE, 0,
1577                                 next_xfer)) {
1578                         umass_bbb_reset(sc, STATUS_WIRE_FAILED);
1579                         return;
1580                 }
1581
1582                 return;
1583         case TSTATE_BBB_STATUS1:        /* first attempt */
1584         case TSTATE_BBB_STATUS2:        /* second attempt */
1585                 /* Status transfer, error handling */
1586                 {
1587                 int Residue;
1588                 if (err) {
1589                         DPRINTF(UDMASS_BBB, ("%s: Failed to read CSW, %s%s\n",
1590                                 device_get_nameunit(sc->sc_dev), usbd_errstr(err),
1591                                 (sc->transfer_state == TSTATE_BBB_STATUS1?
1592                                         ", retrying":"")));
1593
1594                         /* If this was the first attempt at fetching the CSW
1595                          * retry it, otherwise fail.
1596                          */
1597                         if (sc->transfer_state == TSTATE_BBB_STATUS1) {
1598                                 umass_clear_endpoint_stall(sc,
1599                                             sc->bulkin, sc->bulkin_pipe,
1600                                             TSTATE_BBB_SCLEAR,
1601                                             sc->transfer_xfer[XFER_BBB_SCLEAR]);
1602                                 return;
1603                         } else {
1604                                 umass_bbb_reset(sc, STATUS_WIRE_FAILED);
1605                                 return;
1606                         }
1607                 }
1608
1609                 DIF(UDMASS_BBB, umass_bbb_dump_csw(sc, &sc->csw));
1610
1611                 /* Translate weird command-status signatures. */
1612                 if ((sc->quirks & WRONG_CSWSIG) &&
1613                     UGETDW(sc->csw.dCSWSignature) == CSWSIGNATURE_OLYMPUS_C1)
1614                         USETDW(sc->csw.dCSWSignature, CSWSIGNATURE);
1615
1616                 Residue = UGETDW(sc->csw.dCSWDataResidue);
1617                 if (Residue == 0 &&
1618                     sc->transfer_datalen - sc->transfer_actlen != 0)
1619                         Residue = sc->transfer_datalen - sc->transfer_actlen;
1620
1621                 /* Check CSW and handle any error */
1622                 if (UGETDW(sc->csw.dCSWSignature) != CSWSIGNATURE) {
1623                         /* Invalid CSW: Wrong signature or wrong tag might
1624                          * indicate that the device is confused -> reset it.
1625                          */
1626                         kprintf("%s: Invalid CSW: sig 0x%08x should be 0x%08x\n",
1627                                 device_get_nameunit(sc->sc_dev),
1628                                 UGETDW(sc->csw.dCSWSignature),
1629                                 CSWSIGNATURE);
1630
1631                         umass_bbb_reset(sc, STATUS_WIRE_FAILED);
1632                         return;
1633                 } else if (UGETDW(sc->csw.dCSWTag)
1634                                 != UGETDW(sc->cbw.dCBWTag)) {
1635                         kprintf("%s: Invalid CSW: tag %d should be %d\n",
1636                                 device_get_nameunit(sc->sc_dev),
1637                                 UGETDW(sc->csw.dCSWTag),
1638                                 UGETDW(sc->cbw.dCBWTag));
1639
1640                         umass_bbb_reset(sc, STATUS_WIRE_FAILED);
1641                         return;
1642
1643                 /* CSW is valid here */
1644                 } else if (sc->csw.bCSWStatus > CSWSTATUS_PHASE) {
1645                         kprintf("%s: Invalid CSW: status %d > %d\n",
1646                                 device_get_nameunit(sc->sc_dev),
1647                                 sc->csw.bCSWStatus,
1648                                 CSWSTATUS_PHASE);
1649
1650                         umass_bbb_reset(sc, STATUS_WIRE_FAILED);
1651                         return;
1652                 } else if (sc->csw.bCSWStatus == CSWSTATUS_PHASE) {
1653                         kprintf("%s: Phase Error, residue = %d\n",
1654                                 device_get_nameunit(sc->sc_dev), Residue);
1655
1656                         umass_bbb_reset(sc, STATUS_WIRE_FAILED);
1657                         return;
1658
1659                 } else if (sc->transfer_actlen > sc->transfer_datalen) {
1660                         /* Buffer overrun! Don't let this go by unnoticed */
1661                         panic("%s: transferred %db instead of %db",
1662                                 device_get_nameunit(sc->sc_dev),
1663                                 sc->transfer_actlen, sc->transfer_datalen);
1664
1665                 } else if (sc->csw.bCSWStatus == CSWSTATUS_FAILED) {
1666                         DPRINTF(UDMASS_BBB, ("%s: Command Failed, res = %d\n",
1667                                 device_get_nameunit(sc->sc_dev), Residue));
1668
1669                         /* SCSI command failed but transfer was succesful */
1670                         sc->transfer_state = TSTATE_IDLE;
1671                         sc->transfer_cb(sc, sc->transfer_priv, Residue,
1672                                         STATUS_CMD_FAILED);
1673                         return;
1674
1675                 } else {        /* success */
1676                         sc->transfer_state = TSTATE_IDLE;
1677                         sc->transfer_cb(sc, sc->transfer_priv, Residue,
1678                                         STATUS_CMD_OK);
1679
1680                         return;
1681                 }
1682                 }
1683
1684         /***** Bulk Reset *****/
1685         case TSTATE_BBB_RESET1:
1686                 if (err)
1687                         kprintf("%s: BBB reset failed, %s\n",
1688                                 device_get_nameunit(sc->sc_dev), usbd_errstr(err));
1689
1690                 umass_clear_endpoint_stall(sc,
1691                         sc->bulkin, sc->bulkin_pipe, TSTATE_BBB_RESET2,
1692                         sc->transfer_xfer[XFER_BBB_RESET2]);
1693
1694                 return;
1695         case TSTATE_BBB_RESET2:
1696                 if (err)        /* should not occur */
1697                         kprintf("%s: BBB bulk-in clear stall failed, %s\n",
1698                                device_get_nameunit(sc->sc_dev), usbd_errstr(err));
1699                         /* no error recovery, otherwise we end up in a loop */
1700
1701                 umass_clear_endpoint_stall(sc,
1702                         sc->bulkout, sc->bulkout_pipe, TSTATE_BBB_RESET3,
1703                         sc->transfer_xfer[XFER_BBB_RESET3]);
1704
1705                 return;
1706         case TSTATE_BBB_RESET3:
1707                 if (err)        /* should not occur */
1708                         kprintf("%s: BBB bulk-out clear stall failed, %s\n",
1709                                device_get_nameunit(sc->sc_dev), usbd_errstr(err));
1710                         /* no error recovery, otherwise we end up in a loop */
1711
1712                 sc->transfer_state = TSTATE_IDLE;
1713                 if (sc->transfer_priv) {
1714                         sc->transfer_cb(sc, sc->transfer_priv,
1715                                         sc->transfer_datalen,
1716                                         sc->transfer_status);
1717                 }
1718
1719                 return;
1720
1721         /***** Default *****/
1722         default:
1723                 panic("%s: Unknown state %d",
1724                       device_get_nameunit(sc->sc_dev), sc->transfer_state);
1725         }
1726 }
1727
1728 static int
1729 umass_bbb_get_max_lun(struct umass_softc *sc)
1730 {
1731         usbd_device_handle udev;
1732         usb_device_request_t req;
1733         usbd_status err;
1734         usb_interface_descriptor_t *id;
1735         int maxlun = 0;
1736         u_int8_t buf = 0;
1737
1738         usbd_interface2device_handle(sc->iface, &udev);
1739         id = usbd_get_interface_descriptor(sc->iface);
1740
1741         /* The Get Max Lun command is a class-specific request. */
1742         req.bmRequestType = UT_READ_CLASS_INTERFACE;
1743         req.bRequest = UR_BBB_GET_MAX_LUN;
1744         USETW(req.wValue, 0);
1745         USETW(req.wIndex, id->bInterfaceNumber);
1746         USETW(req.wLength, 1);
1747
1748         err = usbd_do_request(udev, &req, &buf);
1749         switch (err) {
1750         case USBD_NORMAL_COMPLETION:
1751                 maxlun = buf;
1752                 DPRINTF(UDMASS_BBB, ("%s: Max Lun is %d\n",
1753                     device_get_nameunit(sc->sc_dev), maxlun));
1754                 break;
1755         case USBD_STALLED:
1756         case USBD_SHORT_XFER:
1757         default:
1758                 /* Device doesn't support Get Max Lun request. */
1759                 kprintf("%s: Get Max Lun not supported (%s)\n",
1760                     device_get_nameunit(sc->sc_dev), usbd_errstr(err));
1761                 /* XXX Should we port_reset the device? */
1762                 break;
1763         }
1764
1765         return(maxlun);
1766 }
1767
1768 /*
1769  * Command/Bulk/Interrupt (CBI) specific functions
1770  */
1771
1772 static int
1773 umass_cbi_adsc(struct umass_softc *sc, char *buffer, int buflen,
1774                usbd_xfer_handle xfer)
1775 {
1776         usbd_device_handle udev;
1777
1778         KASSERT(sc->proto & (UMASS_PROTO_CBI|UMASS_PROTO_CBI_I),
1779                 ("%s: umass_cbi_adsc: wrong sc->proto 0x%02x\n",
1780                         device_get_nameunit(sc->sc_dev), sc->proto));
1781
1782         usbd_interface2device_handle(sc->iface, &udev);
1783
1784         sc->request.bmRequestType = UT_WRITE_CLASS_INTERFACE;
1785         sc->request.bRequest = UR_CBI_ADSC;
1786         USETW(sc->request.wValue, 0);
1787         USETW(sc->request.wIndex, sc->ifaceno);
1788         USETW(sc->request.wLength, buflen);
1789         return umass_setup_ctrl_transfer(sc, udev, &sc->request, buffer,
1790                                          buflen, 0, xfer);
1791 }
1792
1793
1794 static void
1795 umass_cbi_reset(struct umass_softc *sc, int status)
1796 {
1797         int i;
1798 #       define SEND_DIAGNOSTIC_CMDLEN   12
1799
1800         KASSERT(sc->proto & (UMASS_PROTO_CBI|UMASS_PROTO_CBI_I),
1801                 ("%s: umass_cbi_reset: wrong sc->proto 0x%02x\n",
1802                         device_get_nameunit(sc->sc_dev), sc->proto));
1803
1804         /*
1805          * Command Block Reset Protocol
1806          *
1807          * First send a reset request to the device. Then clear
1808          * any possibly stalled bulk endpoints.
1809
1810          * This is done in 3 steps, states:
1811          * TSTATE_CBI_RESET1
1812          * TSTATE_CBI_RESET2
1813          * TSTATE_CBI_RESET3
1814          *
1815          * If the reset doesn't succeed, the device should be port reset.
1816          */
1817
1818         DPRINTF(UDMASS_CBI, ("%s: CBI Reset\n",
1819                 device_get_nameunit(sc->sc_dev)));
1820
1821         KASSERT(sizeof(sc->cbl) >= SEND_DIAGNOSTIC_CMDLEN,
1822                 ("%s: CBL struct is too small (%ld < %d)\n",
1823                         device_get_nameunit(sc->sc_dev),
1824                         (long)sizeof(sc->cbl), SEND_DIAGNOSTIC_CMDLEN));
1825
1826         sc->transfer_state = TSTATE_CBI_RESET1;
1827         sc->transfer_status = status;
1828
1829         /* The 0x1d code is the SEND DIAGNOSTIC command. To distingiush between
1830          * the two the last 10 bytes of the cbl is filled with 0xff (section
1831          * 2.2 of the CBI spec).
1832          */
1833         sc->cbl[0] = 0x1d;      /* Command Block Reset */
1834         sc->cbl[1] = 0x04;
1835         for (i = 2; i < SEND_DIAGNOSTIC_CMDLEN; i++)
1836                 sc->cbl[i] = 0xff;
1837
1838         umass_cbi_adsc(sc, sc->cbl, SEND_DIAGNOSTIC_CMDLEN,
1839                        sc->transfer_xfer[XFER_CBI_RESET1]);
1840         /* XXX if the command fails we should reset the port on the bub */
1841 }
1842
1843 static void
1844 umass_cbi_transfer(struct umass_softc *sc, int lun,
1845                 void *cmd, int cmdlen, void *data, int datalen, int dir,
1846                 transfer_cb_f cb, void *priv)
1847 {
1848         KASSERT(sc->proto & (UMASS_PROTO_CBI|UMASS_PROTO_CBI_I),
1849                 ("%s: umass_cbi_transfer: wrong sc->proto 0x%02x\n",
1850                         device_get_nameunit(sc->sc_dev), sc->proto));
1851
1852         /*
1853          * Do a CBI transfer with cmdlen bytes from cmd, possibly
1854          * a data phase of datalen bytes from/to the device and finally a
1855          * csw read phase.
1856          * If the data direction was inbound a maximum of datalen bytes
1857          * is stored in the buffer pointed to by data.
1858          *
1859          * umass_cbi_transfer initialises the transfer and lets the state
1860          * machine in umass_cbi_state handle the completion. It uses the
1861          * following states:
1862          * TSTATE_CBI_COMMAND
1863          *   -> XXX fill in
1864          *
1865          * An error in any of those states will invoke
1866          * umass_cbi_reset.
1867          */
1868
1869         /* check the given arguments */
1870         KASSERT(datalen == 0 || data != NULL,
1871                 ("%s: datalen > 0, but no buffer",device_get_nameunit(sc->sc_dev)));
1872         KASSERT(datalen == 0 || dir != DIR_NONE,
1873                 ("%s: direction is NONE while datalen is not zero\n",
1874                         device_get_nameunit(sc->sc_dev)));
1875
1876         /* store the details for the data transfer phase */
1877         sc->transfer_dir = dir;
1878         sc->transfer_data = data;
1879         sc->transfer_datalen = datalen;
1880         sc->transfer_actlen = 0;
1881         sc->transfer_cb = cb;
1882         sc->transfer_priv = priv;
1883         sc->transfer_status = STATUS_CMD_OK;
1884
1885         /* move from idle to the command state */
1886         sc->transfer_state = TSTATE_CBI_COMMAND;
1887
1888         DIF(UDMASS_CBI, umass_cbi_dump_cmd(sc, cmd, cmdlen));
1889
1890         /* Send the Command Block from host to device via control endpoint. */
1891         if (umass_cbi_adsc(sc, cmd, cmdlen, sc->transfer_xfer[XFER_CBI_CB]))
1892                 umass_cbi_reset(sc, STATUS_WIRE_FAILED);
1893 }
1894
1895 static void
1896 umass_cbi_state(usbd_xfer_handle xfer, usbd_private_handle priv,
1897                 usbd_status err)
1898 {
1899         struct umass_softc *sc = (struct umass_softc *) priv;
1900
1901         KASSERT(sc->proto & (UMASS_PROTO_CBI|UMASS_PROTO_CBI_I),
1902                 ("%s: umass_cbi_state: wrong sc->proto 0x%02x\n",
1903                         device_get_nameunit(sc->sc_dev), sc->proto));
1904
1905         /*
1906          * State handling for CBI transfers.
1907          */
1908
1909         DPRINTF(UDMASS_CBI, ("%s: Handling CBI state %d (%s), xfer=%p, %s\n",
1910                 device_get_nameunit(sc->sc_dev), sc->transfer_state,
1911                 states[sc->transfer_state], xfer, usbd_errstr(err)));
1912
1913         switch (sc->transfer_state) {
1914
1915         /***** CBI Transfer *****/
1916         case TSTATE_CBI_COMMAND:
1917                 if (err == USBD_STALLED) {
1918                         DPRINTF(UDMASS_CBI, ("%s: Command Transport failed\n",
1919                                 device_get_nameunit(sc->sc_dev)));
1920                         /* Status transport by control pipe (section 2.3.2.1).
1921                          * The command contained in the command block failed.
1922                          *
1923                          * The control pipe has already been unstalled by the
1924                          * USB stack.
1925                          * Section 2.4.3.1.1 states that the bulk in endpoints
1926                          * should not be stalled at this point.
1927                          */
1928
1929                         sc->transfer_state = TSTATE_IDLE;
1930                         sc->transfer_cb(sc, sc->transfer_priv,
1931                                         sc->transfer_datalen,
1932                                         STATUS_CMD_FAILED);
1933
1934                         return;
1935                 } else if (err) {
1936                         DPRINTF(UDMASS_CBI, ("%s: failed to send ADSC\n",
1937                                 device_get_nameunit(sc->sc_dev)));
1938                         umass_cbi_reset(sc, STATUS_WIRE_FAILED);
1939
1940                         return;
1941                 }
1942
1943                 sc->transfer_state = TSTATE_CBI_DATA;
1944                 if (sc->transfer_dir == DIR_IN) {
1945                         if (umass_setup_transfer(sc, sc->bulkin_pipe,
1946                                         sc->transfer_data, sc->transfer_datalen,
1947                                         USBD_SHORT_XFER_OK,
1948                                         sc->transfer_xfer[XFER_CBI_DATA]))
1949                                 umass_cbi_reset(sc, STATUS_WIRE_FAILED);
1950
1951                 } else if (sc->transfer_dir == DIR_OUT) {
1952                         if (umass_setup_transfer(sc, sc->bulkout_pipe,
1953                                         sc->transfer_data, sc->transfer_datalen,
1954                                         0,      /* fixed length transfer */
1955                                         sc->transfer_xfer[XFER_CBI_DATA]))
1956                                 umass_cbi_reset(sc, STATUS_WIRE_FAILED);
1957
1958                 } else if (sc->proto & UMASS_PROTO_CBI_I) {
1959                         DPRINTF(UDMASS_CBI, ("%s: no data phase\n",
1960                                 device_get_nameunit(sc->sc_dev)));
1961                         sc->transfer_state = TSTATE_CBI_STATUS;
1962                         if (umass_setup_transfer(sc, sc->intrin_pipe,
1963                                         &sc->sbl, sizeof(sc->sbl),
1964                                         0,      /* fixed length transfer */
1965                                         sc->transfer_xfer[XFER_CBI_STATUS])){
1966                                 umass_cbi_reset(sc, STATUS_WIRE_FAILED);
1967                         }
1968                 } else {
1969                         DPRINTF(UDMASS_CBI, ("%s: no data phase\n",
1970                                 device_get_nameunit(sc->sc_dev)));
1971                         /* No command completion interrupt. Request
1972                          * sense data.
1973                          */
1974                         sc->transfer_state = TSTATE_IDLE;
1975                         sc->transfer_cb(sc, sc->transfer_priv,
1976                                0, STATUS_CMD_UNKNOWN);
1977                 }
1978
1979                 return;
1980
1981         case TSTATE_CBI_DATA:
1982                 /* retrieve the length of the transfer that was done */
1983                 usbd_get_xfer_status(xfer,NULL,NULL,&sc->transfer_actlen,NULL);
1984
1985                 if (err) {
1986                         DPRINTF(UDMASS_CBI, ("%s: Data-%s %db failed, "
1987                                 "%s\n", device_get_nameunit(sc->sc_dev),
1988                                 (sc->transfer_dir == DIR_IN?"in":"out"),
1989                                 sc->transfer_datalen,usbd_errstr(err)));
1990
1991                         if (err == USBD_STALLED) {
1992                                 umass_clear_endpoint_stall(sc,
1993                                         sc->bulkin, sc->bulkin_pipe,
1994                                         TSTATE_CBI_DCLEAR,
1995                                         sc->transfer_xfer[XFER_CBI_DCLEAR]);
1996                         } else {
1997                                 umass_cbi_reset(sc, STATUS_WIRE_FAILED);
1998                         }
1999                         return;
2000                 }
2001
2002                 DIF(UDMASS_CBI, if (sc->transfer_dir == DIR_IN)
2003                                         umass_dump_buffer(sc, sc->transfer_data,
2004                                                 sc->transfer_actlen, 48));
2005
2006                 if (sc->proto & UMASS_PROTO_CBI_I) {
2007                         sc->transfer_state = TSTATE_CBI_STATUS;
2008                         if (umass_setup_transfer(sc, sc->intrin_pipe,
2009                                     &sc->sbl, sizeof(sc->sbl),
2010                                     0,  /* fixed length transfer */
2011                                     sc->transfer_xfer[XFER_CBI_STATUS])){
2012                                 umass_cbi_reset(sc, STATUS_WIRE_FAILED);
2013                         }
2014                 } else {
2015                         /* No command completion interrupt. Request
2016                          * sense to get status of command.
2017                          */
2018                         sc->transfer_state = TSTATE_IDLE;
2019                         sc->transfer_cb(sc, sc->transfer_priv,
2020                                 sc->transfer_datalen - sc->transfer_actlen,
2021                                 STATUS_CMD_UNKNOWN);
2022                 }
2023                 return;
2024
2025         case TSTATE_CBI_STATUS:
2026                 if (err) {
2027                         DPRINTF(UDMASS_CBI, ("%s: Status Transport failed\n",
2028                                 device_get_nameunit(sc->sc_dev)));
2029                         /* Status transport by interrupt pipe (section 2.3.2.2).
2030                          */
2031
2032                         if (err == USBD_STALLED) {
2033                                 umass_clear_endpoint_stall(sc,
2034                                         sc->intrin, sc->intrin_pipe,
2035                                         TSTATE_CBI_SCLEAR,
2036                                         sc->transfer_xfer[XFER_CBI_SCLEAR]);
2037                         } else {
2038                                 umass_cbi_reset(sc, STATUS_WIRE_FAILED);
2039                         }
2040                         return;
2041                 }
2042
2043                 /* Dissect the information in the buffer */
2044
2045                 if (sc->proto & UMASS_PROTO_UFI) {
2046                         int status;
2047
2048                         /* Section 3.4.3.1.3 specifies that the UFI command
2049                          * protocol returns an ASC and ASCQ in the interrupt
2050                          * data block.
2051                          */
2052
2053                         DPRINTF(UDMASS_CBI, ("%s: UFI CCI, ASC = 0x%02x, "
2054                                 "ASCQ = 0x%02x\n",
2055                                 device_get_nameunit(sc->sc_dev),
2056                                 sc->sbl.ufi.asc, sc->sbl.ufi.ascq));
2057
2058                         if (sc->sbl.ufi.asc == 0 && sc->sbl.ufi.ascq == 0)
2059                                 status = STATUS_CMD_OK;
2060                         else
2061                                 status = STATUS_CMD_FAILED;
2062
2063                         sc->transfer_state = TSTATE_IDLE;
2064                         sc->transfer_cb(sc, sc->transfer_priv,
2065                                 sc->transfer_datalen - sc->transfer_actlen,
2066                                 status);
2067                 } else {
2068                         /* Command Interrupt Data Block */
2069                         DPRINTF(UDMASS_CBI, ("%s: type=0x%02x, value=0x%02x\n",
2070                                 device_get_nameunit(sc->sc_dev),
2071                                 sc->sbl.common.type, sc->sbl.common.value));
2072
2073                         if (sc->sbl.common.type == IDB_TYPE_CCI) {
2074                                 int err;
2075
2076                                 if ((sc->sbl.common.value&IDB_VALUE_STATUS_MASK)
2077                                                         == IDB_VALUE_PASS) {
2078                                         err = STATUS_CMD_OK;
2079                                 } else if ((sc->sbl.common.value & IDB_VALUE_STATUS_MASK)
2080                                                         == IDB_VALUE_FAIL ||
2081                                            (sc->sbl.common.value & IDB_VALUE_STATUS_MASK)
2082                                                 == IDB_VALUE_PERSISTENT) {
2083                                         err = STATUS_CMD_FAILED;
2084                                 } else {
2085                                         err = STATUS_WIRE_FAILED;
2086                                 }
2087
2088                                 sc->transfer_state = TSTATE_IDLE;
2089                                 sc->transfer_cb(sc, sc->transfer_priv,
2090                                        sc->transfer_datalen-sc->transfer_actlen,
2091                                        err);
2092                         }
2093                 }
2094                 return;
2095
2096         case TSTATE_CBI_DCLEAR:
2097                 if (err) {      /* should not occur */
2098                         kprintf("%s: CBI bulk-in/out stall clear failed, %s\n",
2099                                device_get_nameunit(sc->sc_dev), usbd_errstr(err));
2100                         umass_cbi_reset(sc, STATUS_WIRE_FAILED);
2101                 }
2102
2103                 sc->transfer_state = TSTATE_IDLE;
2104                 sc->transfer_cb(sc, sc->transfer_priv,
2105                                 sc->transfer_datalen,
2106                                 STATUS_CMD_FAILED);
2107                 return;
2108
2109         case TSTATE_CBI_SCLEAR:
2110                 if (err)        /* should not occur */
2111                         kprintf("%s: CBI intr-in stall clear failed, %s\n",
2112                                device_get_nameunit(sc->sc_dev), usbd_errstr(err));
2113
2114                 /* Something really bad is going on. Reset the device */
2115                 umass_cbi_reset(sc, STATUS_CMD_FAILED);
2116                 return;
2117
2118         /***** CBI Reset *****/
2119         case TSTATE_CBI_RESET1:
2120                 if (err)
2121                         kprintf("%s: CBI reset failed, %s\n",
2122                                 device_get_nameunit(sc->sc_dev), usbd_errstr(err));
2123
2124                 umass_clear_endpoint_stall(sc,
2125                         sc->bulkin, sc->bulkin_pipe, TSTATE_CBI_RESET2,
2126                         sc->transfer_xfer[XFER_CBI_RESET2]);
2127
2128                 return;
2129         case TSTATE_CBI_RESET2:
2130                 if (err)        /* should not occur */
2131                         kprintf("%s: CBI bulk-in stall clear failed, %s\n",
2132                                device_get_nameunit(sc->sc_dev), usbd_errstr(err));
2133                         /* no error recovery, otherwise we end up in a loop */
2134
2135                 umass_clear_endpoint_stall(sc,
2136                         sc->bulkout, sc->bulkout_pipe, TSTATE_CBI_RESET3,
2137                         sc->transfer_xfer[XFER_CBI_RESET3]);
2138
2139                 return;
2140         case TSTATE_CBI_RESET3:
2141                 if (err)        /* should not occur */
2142                         kprintf("%s: CBI bulk-out stall clear failed, %s\n",
2143                                device_get_nameunit(sc->sc_dev), usbd_errstr(err));
2144                         /* no error recovery, otherwise we end up in a loop */
2145
2146                 sc->transfer_state = TSTATE_IDLE;
2147                 if (sc->transfer_priv) {
2148                         sc->transfer_cb(sc, sc->transfer_priv,
2149                                         sc->transfer_datalen,
2150                                         sc->transfer_status);
2151                 }
2152
2153                 return;
2154
2155
2156         /***** Default *****/
2157         default:
2158                 panic("%s: Unknown state %d",
2159                       device_get_nameunit(sc->sc_dev), sc->transfer_state);
2160         }
2161 }
2162
2163
2164
2165
2166 /*
2167  * CAM specific functions (used by SCSI, UFI, 8070i (ATAPI))
2168  */
2169
2170 static int
2171 umass_cam_attach_sim(struct umass_softc *sc)
2172 {
2173         struct cam_devq *devq;          /* Per device Queue */
2174
2175         /* A HBA is attached to the CAM layer.
2176          *
2177          * The CAM layer will then after a while start probing for
2178          * devices on the bus. The number of SIMs is limited to one.
2179          */
2180
2181         callout_init(&sc->rescan_timeout);
2182         devq = cam_simq_alloc(1 /*maximum openings*/);
2183         if (devq == NULL)
2184                 return(ENOMEM);
2185
2186         sc->umass_sim = cam_sim_alloc(umass_cam_action, umass_cam_poll,
2187                                 DEVNAME_SIM,
2188                                 sc /*priv*/,
2189                                 device_get_unit(sc->sc_dev) /*unit number*/,
2190                                 1 /*maximum device openings*/,
2191                                 0 /*maximum tagged device openings*/,
2192                                 devq);
2193         cam_simq_release(devq);
2194         if (sc->umass_sim == NULL)
2195                 return(ENOMEM);
2196
2197         /*
2198          * If we could not register the bus we must immediately free the
2199          * sim so we do not attempt to deregister a bus later on that we
2200          * had not registered.
2201          */
2202         if (xpt_bus_register(sc->umass_sim, device_get_unit(sc->sc_dev)) !=
2203             CAM_SUCCESS) {
2204                 cam_sim_free(sc->umass_sim);
2205                 sc->umass_sim = NULL;
2206                 return(ENOMEM);
2207         }
2208
2209         return(0);
2210 }
2211
2212 static void
2213 umass_cam_rescan_callback(struct cam_periph *periph, union ccb *ccb)
2214 {
2215 #ifdef USB_DEBUG
2216         if (ccb->ccb_h.status != CAM_REQ_CMP) {
2217                 DPRINTF(UDMASS_SCSI, ("%s:%d Rescan failed, 0x%04x\n",
2218                         periph->periph_name, periph->unit_number,
2219                         ccb->ccb_h.status));
2220         } else {
2221                 DPRINTF(UDMASS_SCSI, ("%s%d: Rescan succeeded\n",
2222                         periph->periph_name, periph->unit_number));
2223         }
2224 #endif
2225
2226         xpt_free_path(ccb->ccb_h.path);
2227         kfree(ccb, M_USBDEV);
2228 }
2229
2230 static void
2231 umass_cam_rescan(void *addr)
2232 {
2233         struct umass_softc *sc = (struct umass_softc *) addr;
2234         struct cam_path *path;
2235         union ccb *ccb;
2236
2237         ccb = kmalloc(sizeof(union ccb), M_USBDEV, M_INTWAIT|M_ZERO);
2238
2239         DPRINTF(UDMASS_SCSI, ("scbus%d: scanning for %s:%d:%d:%d\n",
2240                 cam_sim_path(sc->umass_sim),
2241                 device_get_nameunit(sc->sc_dev), cam_sim_path(sc->umass_sim),
2242                 device_get_unit(sc->sc_dev), CAM_LUN_WILDCARD));
2243
2244         if (xpt_create_path(&path, xpt_periph, cam_sim_path(sc->umass_sim),
2245                             CAM_TARGET_WILDCARD, CAM_LUN_WILDCARD)
2246             != CAM_REQ_CMP) {
2247                 kfree(ccb, M_USBDEV);
2248                 return;
2249         }
2250
2251         xpt_setup_ccb(&ccb->ccb_h, path, 5/*priority (low)*/);
2252         ccb->ccb_h.func_code = XPT_SCAN_BUS;
2253         ccb->ccb_h.cbfcnp = umass_cam_rescan_callback;
2254         ccb->crcn.flags = CAM_FLAG_NONE;
2255         xpt_action(ccb);
2256
2257         /* The scan is in progress now. */
2258 }
2259
2260 static int
2261 umass_cam_attach(struct umass_softc *sc)
2262 {
2263 #ifndef USB_DEBUG
2264         if (bootverbose)
2265 #endif
2266                 kprintf("%s:%d:%d:%d: Attached to scbus%d\n",
2267                         device_get_nameunit(sc->sc_dev), cam_sim_path(sc->umass_sim),
2268                         device_get_unit(sc->sc_dev), CAM_LUN_WILDCARD,
2269                         cam_sim_path(sc->umass_sim));
2270
2271         if (!cold) {
2272                 /* 
2273                  * Notify CAM of the new device after a 0.2 second delay. Any
2274                  * failure is benign, as the user can still do it by hand
2275                  * (camcontrol rescan <busno>). Only do this if we are not
2276                  * booting, because CAM does a scan after booting has
2277                  * completed, when interrupts have been enabled.
2278                  */
2279                 callout_reset(&sc->rescan_timeout, MS_TO_TICKS(200),
2280                                 umass_cam_rescan, sc);
2281         }
2282
2283         return(0);      /* always succesfull */
2284 }
2285
2286 /* umass_cam_detach
2287  *      detach from the CAM layer
2288  */
2289
2290 static int
2291 umass_cam_detach_sim(struct umass_softc *sc)
2292 {
2293         callout_stop(&sc->rescan_timeout);
2294         if (sc->umass_sim) {
2295                 xpt_bus_deregister(cam_sim_path(sc->umass_sim));
2296                 cam_sim_free(sc->umass_sim);
2297
2298                 sc->umass_sim = NULL;
2299         }
2300
2301         return(0);
2302 }
2303
2304 /* umass_cam_action
2305  *      CAM requests for action come through here
2306  */
2307
2308 static void
2309 umass_cam_action(struct cam_sim *sim, union ccb *ccb)
2310 {
2311         struct umass_softc *sc = (struct umass_softc *)sim->softc;
2312
2313         /* The softc is still there, but marked as going away. umass_cam_detach
2314          * has not yet notified CAM of the lost device however.
2315          */
2316         if (sc && (sc->flags & UMASS_FLAGS_GONE)) {
2317                 DPRINTF(UDMASS_SCSI, ("%s:%d:%d:%d:func_code 0x%04x: "
2318                         "Invalid target (gone)\n",
2319                         device_get_nameunit(sc->sc_dev), cam_sim_path(sc->umass_sim),
2320                         ccb->ccb_h.target_id, ccb->ccb_h.target_lun,
2321                         ccb->ccb_h.func_code));
2322                 ccb->ccb_h.status = CAM_TID_INVALID;
2323                 xpt_done(ccb);
2324                 return;
2325         }
2326
2327         /* Verify, depending on the operation to perform, that we either got a
2328          * valid sc, because an existing target was referenced, or otherwise
2329          * the SIM is addressed.
2330          *
2331          * This avoids bombing out at a kprintf and does give the CAM layer some
2332          * sensible feedback on errors.
2333          */
2334         switch (ccb->ccb_h.func_code) {
2335         case XPT_SCSI_IO:
2336         case XPT_RESET_DEV:
2337         case XPT_GET_TRAN_SETTINGS:
2338         case XPT_SET_TRAN_SETTINGS:
2339         case XPT_CALC_GEOMETRY:
2340                 /* the opcodes requiring a target. These should never occur. */
2341                 if (sc == NULL) {
2342                         kprintf("%s:%d:%d:%d:func_code 0x%04x: "
2343                                 "Invalid target (target needed)\n",
2344                                 DEVNAME_SIM, cam_sim_path(sc->umass_sim),
2345                                 ccb->ccb_h.target_id, ccb->ccb_h.target_lun,
2346                                 ccb->ccb_h.func_code);
2347
2348                         ccb->ccb_h.status = CAM_TID_INVALID;
2349                         xpt_done(ccb);
2350                         return;
2351                 }
2352                 break;
2353         case XPT_PATH_INQ:
2354         case XPT_NOOP:
2355                 /* The opcodes sometimes aimed at a target (sc is valid),
2356                  * sometimes aimed at the SIM (sc is invalid and target is
2357                  * CAM_TARGET_WILDCARD)
2358                  */
2359                 if (sc == NULL && ccb->ccb_h.target_id != CAM_TARGET_WILDCARD) {
2360                         DPRINTF(UDMASS_SCSI, ("%s:%d:%d:%d:func_code 0x%04x: "
2361                                 "Invalid target (no wildcard)\n",
2362                                 DEVNAME_SIM, cam_sim_path(sc->umass_sim),
2363                                 ccb->ccb_h.target_id, ccb->ccb_h.target_lun,
2364                                 ccb->ccb_h.func_code));
2365
2366                         ccb->ccb_h.status = CAM_TID_INVALID;
2367                         xpt_done(ccb);
2368                         return;
2369                 }
2370                 break;
2371         default:
2372                 /* XXX Hm, we should check the input parameters */
2373                 break;
2374         }
2375
2376         /* Perform the requested action */
2377         switch (ccb->ccb_h.func_code) {
2378         case XPT_SCSI_IO:
2379         {
2380                 struct ccb_scsiio *csio = &ccb->csio;   /* deref union */
2381                 int dir;
2382                 unsigned char *cmd;
2383                 int cmdlen;
2384                 unsigned char *rcmd;
2385                 int rcmdlen;
2386
2387                 DPRINTF(UDMASS_SCSI, ("%s:%d:%d:%d:XPT_SCSI_IO: "
2388                         "cmd: 0x%02x, flags: 0x%02x, "
2389                         "%db cmd/%db data/%db sense\n",
2390                         device_get_nameunit(sc->sc_dev), cam_sim_path(sc->umass_sim),
2391                         ccb->ccb_h.target_id, ccb->ccb_h.target_lun,
2392                         csio->cdb_io.cdb_bytes[0],
2393                         ccb->ccb_h.flags & CAM_DIR_MASK,
2394                         csio->cdb_len, csio->dxfer_len,
2395                         csio->sense_len));
2396
2397                 /* clear the end of the buffer to make sure we don't send out
2398                  * garbage.
2399                  */
2400                 DIF(UDMASS_SCSI, if ((ccb->ccb_h.flags & CAM_DIR_MASK)
2401                                      == CAM_DIR_OUT)
2402                                         umass_dump_buffer(sc, csio->data_ptr,
2403                                                 csio->dxfer_len, 48));
2404
2405                 if (sc->transfer_state != TSTATE_IDLE) {
2406                         DPRINTF(UDMASS_SCSI, ("%s:%d:%d:%d:XPT_SCSI_IO: "
2407                                 "I/O in progress, deferring (state %d, %s)\n",
2408                                 device_get_nameunit(sc->sc_dev), cam_sim_path(sc->umass_sim),
2409                                 ccb->ccb_h.target_id, ccb->ccb_h.target_lun,
2410                                 sc->transfer_state,states[sc->transfer_state]));
2411                         ccb->ccb_h.status = CAM_SCSI_BUSY;
2412                         xpt_done(ccb);
2413                         return;
2414                 }
2415
2416                 switch(ccb->ccb_h.flags&CAM_DIR_MASK) {
2417                 case CAM_DIR_IN:
2418                         dir = DIR_IN;
2419                         break;
2420                 case CAM_DIR_OUT:
2421                         dir = DIR_OUT;
2422                         break;
2423                 default:
2424                         dir = DIR_NONE;
2425                 }
2426
2427                 ccb->ccb_h.status = CAM_REQ_INPROG | CAM_SIM_QUEUED;
2428
2429
2430                 if (csio->ccb_h.flags & CAM_CDB_POINTER) {
2431                         cmd = (unsigned char *) csio->cdb_io.cdb_ptr;
2432                 } else {
2433                         cmd = (unsigned char *) &csio->cdb_io.cdb_bytes;
2434                 }
2435                 cmdlen = csio->cdb_len;
2436                 rcmd = (unsigned char *) &sc->cam_scsi_command;
2437                 rcmdlen = sizeof(sc->cam_scsi_command);
2438
2439                 /* sc->transform will convert the command to the command
2440                  * (format) needed by the specific command set and return
2441                  * the converted command in a buffer pointed to be rcmd.
2442                  * We pass in a buffer, but if the command does not
2443                  * have to be transformed it returns a ptr to the original
2444                  * buffer (see umass_scsi_transform).
2445                  */
2446
2447                 if (sc->transform(sc, cmd, cmdlen, &rcmd, &rcmdlen)) {
2448                         /*
2449                          * Handle EVPD inquiry for broken devices first
2450                          * NO_INQUIRY also implies NO_INQUIRY_EVPD
2451                          */
2452                         if ((sc->quirks & (NO_INQUIRY_EVPD | NO_INQUIRY)) &&
2453                             rcmd[0] == INQUIRY && (rcmd[1] & SI_EVPD)) {
2454                                 struct scsi_sense_data *sense;
2455
2456                                 sense = &ccb->csio.sense_data;
2457                                 bzero(sense, sizeof(*sense));
2458                                 sense->error_code = SSD_CURRENT_ERROR;
2459                                 sense->flags = SSD_KEY_ILLEGAL_REQUEST;
2460                                 sense->add_sense_code = 0x24;
2461                                 sense->extra_len = 10;
2462                                 ccb->csio.scsi_status = SCSI_STATUS_CHECK_COND;
2463                                 ccb->ccb_h.status = CAM_SCSI_STATUS_ERROR |
2464                                     CAM_AUTOSNS_VALID;
2465                                 xpt_done(ccb);
2466                                 return;
2467                         }
2468                         /* Return fake inquiry data for broken devices */
2469                         if ((sc->quirks & NO_INQUIRY) && rcmd[0] == INQUIRY) {
2470                                 struct ccb_scsiio *csio = &ccb->csio;
2471
2472                                 memcpy(csio->data_ptr, &fake_inq_data,
2473                                     sizeof(fake_inq_data));
2474                                 csio->scsi_status = SCSI_STATUS_OK;
2475                                 ccb->ccb_h.status = CAM_REQ_CMP;
2476                                 xpt_done(ccb);
2477                                 return;
2478                         }
2479                         if ((sc->quirks & FORCE_SHORT_INQUIRY) &&
2480                             rcmd[0] == INQUIRY) {
2481                                 csio->dxfer_len = SHORT_INQUIRY_LENGTH;
2482                         }
2483                         sc->transfer(sc, ccb->ccb_h.target_lun, rcmd, rcmdlen,
2484                                      csio->data_ptr,
2485                                      csio->dxfer_len, dir,
2486                                      umass_cam_cb, (void *) ccb);
2487                 } else {
2488                         ccb->ccb_h.status = CAM_REQ_INVALID;
2489                         xpt_done(ccb);
2490                 }
2491
2492                 break;
2493         }
2494         case XPT_PATH_INQ:
2495         {
2496                 struct ccb_pathinq *cpi = &ccb->cpi;
2497
2498                 DPRINTF(UDMASS_SCSI, ("%s:%d:%d:%d:XPT_PATH_INQ:.\n",
2499                         (sc == NULL? DEVNAME_SIM:device_get_nameunit(sc->sc_dev)),
2500                         cam_sim_path(sc->umass_sim),
2501                         ccb->ccb_h.target_id, ccb->ccb_h.target_lun));
2502
2503                 /* host specific information */
2504                 cpi->version_num = 1;
2505                 cpi->hba_inquiry = 0;
2506                 cpi->target_sprt = 0;
2507                 cpi->hba_misc = PIM_NO_6_BYTE;
2508                 cpi->hba_eng_cnt = 0;
2509                 cpi->max_target = UMASS_SCSIID_MAX;     /* one target */
2510                 cpi->initiator_id = UMASS_SCSIID_HOST;
2511                 strncpy(cpi->sim_vid, "FreeBSD", SIM_IDLEN);
2512                 strncpy(cpi->hba_vid, "USB SCSI", HBA_IDLEN);
2513                 strncpy(cpi->dev_name, cam_sim_name(sim), DEV_IDLEN);
2514                 cpi->unit_number = cam_sim_unit(sim);
2515                 cpi->bus_id = device_get_unit(sc->sc_dev);
2516
2517                 if (sc == NULL) {
2518                         cpi->base_transfer_speed = 0;
2519                         cpi->max_lun = 0;
2520                 } else {
2521                         if (sc->quirks & FLOPPY_SPEED) {
2522                             cpi->base_transfer_speed = UMASS_FLOPPY_TRANSFER_SPEED;
2523                         } else {
2524                             cpi->base_transfer_speed = UMASS_DEFAULT_TRANSFER_SPEED;
2525                         }
2526                         cpi->max_lun = sc->maxlun;
2527                 }
2528
2529                 cpi->ccb_h.status = CAM_REQ_CMP;
2530                 xpt_done(ccb);
2531                 break;
2532         }
2533         case XPT_RESET_DEV:
2534         {
2535                 DPRINTF(UDMASS_SCSI, ("%s:%d:%d:%d:XPT_RESET_DEV:.\n",
2536                         device_get_nameunit(sc->sc_dev), cam_sim_path(sc->umass_sim),
2537                         ccb->ccb_h.target_id, ccb->ccb_h.target_lun));
2538
2539                 ccb->ccb_h.status = CAM_REQ_INPROG;
2540                 umass_reset(sc, umass_cam_cb, (void *) ccb);
2541                 break;
2542         }
2543         case XPT_GET_TRAN_SETTINGS:
2544         {
2545                 struct ccb_trans_settings *cts = &ccb->cts;
2546
2547                 DPRINTF(UDMASS_SCSI, ("%s:%d:%d:%d:XPT_GET_TRAN_SETTINGS:.\n",
2548                         device_get_nameunit(sc->sc_dev), cam_sim_path(sc->umass_sim),
2549                         ccb->ccb_h.target_id, ccb->ccb_h.target_lun));
2550
2551                 cts->valid = 0;
2552                 cts->flags = 0;         /* no disconnection, tagging */
2553
2554                 ccb->ccb_h.status = CAM_REQ_CMP;
2555                 xpt_done(ccb);
2556                 break;
2557         }
2558         case XPT_SET_TRAN_SETTINGS:
2559         {
2560                 DPRINTF(UDMASS_SCSI, ("%s:%d:%d:%d:XPT_SET_TRAN_SETTINGS:.\n",
2561                         device_get_nameunit(sc->sc_dev), cam_sim_path(sc->umass_sim),
2562                         ccb->ccb_h.target_id, ccb->ccb_h.target_lun));
2563
2564                 ccb->ccb_h.status = CAM_FUNC_NOTAVAIL;
2565                 xpt_done(ccb);
2566                 break;
2567         }
2568         case XPT_CALC_GEOMETRY:
2569         {
2570                 cam_calc_geometry(&ccb->ccg, /*extended*/1);
2571                 xpt_done(ccb);
2572                 break;
2573         }
2574         case XPT_NOOP:
2575         {
2576                 DPRINTF(UDMASS_SCSI, ("%s:%d:%d:%d:XPT_NOOP:.\n",
2577                         (sc == NULL? DEVNAME_SIM:device_get_nameunit(sc->sc_dev)),
2578                         cam_sim_path(sc->umass_sim),
2579                         ccb->ccb_h.target_id, ccb->ccb_h.target_lun));
2580
2581                 ccb->ccb_h.status = CAM_REQ_CMP;
2582                 xpt_done(ccb);
2583                 break;
2584         }
2585         default:
2586                 DPRINTF(UDMASS_SCSI, ("%s:%d:%d:%d:func_code 0x%04x: "
2587                         "Not implemented\n",
2588                         (sc == NULL? DEVNAME_SIM:device_get_nameunit(sc->sc_dev)),
2589                         cam_sim_path(sc->umass_sim),
2590                         ccb->ccb_h.target_id, ccb->ccb_h.target_lun,
2591                         ccb->ccb_h.func_code));
2592
2593                 ccb->ccb_h.status = CAM_FUNC_NOTAVAIL;
2594                 xpt_done(ccb);
2595                 break;
2596         }
2597 }
2598
2599 static void
2600 umass_cam_poll(struct cam_sim *sim)
2601 {
2602         struct umass_softc *sc = (struct umass_softc *) sim->softc;
2603
2604         KKASSERT(sc != NULL);
2605
2606         DPRINTF(UDMASS_SCSI, ("%s: CAM poll\n",
2607                 device_get_nameunit(sc->sc_dev)));
2608
2609         usbd_set_polling(sc->sc_udev, 1);
2610         usbd_dopoll(sc->iface);
2611         usbd_set_polling(sc->sc_udev, 0);
2612 }
2613
2614
2615 /* umass_cam_cb
2616  *      finalise a completed CAM command
2617  */
2618
2619 static void
2620 umass_cam_cb(struct umass_softc *sc, void *priv, int residue, int status)
2621 {
2622         union ccb *ccb = (union ccb *) priv;
2623         struct ccb_scsiio *csio = &ccb->csio;           /* deref union */
2624
2625         csio->resid = residue;
2626
2627         switch (status) {
2628         case STATUS_CMD_OK:
2629                 ccb->ccb_h.status = CAM_REQ_CMP;
2630                 xpt_done(ccb);
2631                 break;
2632
2633         case STATUS_CMD_UNKNOWN:
2634         case STATUS_CMD_FAILED:
2635                 switch (ccb->ccb_h.func_code) {
2636                 case XPT_SCSI_IO:
2637                 {
2638                         unsigned char *rcmd;
2639                         int rcmdlen;
2640
2641                         /* fetch sense data */
2642                         /* the rest of the command was filled in at attach */
2643                         sc->cam_scsi_sense.length = csio->sense_len;
2644
2645                         DPRINTF(UDMASS_SCSI,("%s: Fetching %db sense data\n",
2646                                 device_get_nameunit(sc->sc_dev), csio->sense_len));
2647
2648                         rcmd = (unsigned char *) &sc->cam_scsi_command;
2649                         rcmdlen = sizeof(sc->cam_scsi_command);
2650
2651                         if (sc->transform(sc,
2652                                     (unsigned char *) &sc->cam_scsi_sense,
2653                                     sizeof(sc->cam_scsi_sense),
2654                                     &rcmd, &rcmdlen)) {
2655                                 if ((sc->quirks & FORCE_SHORT_INQUIRY) && (rcmd[0] == INQUIRY)) {
2656                                         csio->sense_len = SHORT_INQUIRY_LENGTH;
2657                                 }
2658                                 sc->transfer(sc, ccb->ccb_h.target_lun,
2659                                              rcmd, rcmdlen,
2660                                              &csio->sense_data,
2661                                              csio->sense_len, DIR_IN,
2662                                              umass_cam_sense_cb, (void *) ccb);
2663                         } else {
2664                                 panic("transform(REQUEST_SENSE) failed");
2665                         }
2666                         break;
2667                 }
2668                 case XPT_RESET_DEV: /* Reset failed */
2669                         ccb->ccb_h.status = CAM_REQ_CMP_ERR;
2670                         xpt_done(ccb);
2671                         break;
2672                 default:
2673                         panic("umass_cam_cb called for func_code %d",
2674                               ccb->ccb_h.func_code);
2675                 }
2676                 break;
2677
2678         case STATUS_WIRE_FAILED:
2679                 /* the wire protocol failed and will have recovered
2680                  * (hopefully).  We return an error to CAM and let CAM retry
2681                  * the command if necessary.
2682                  */
2683                 ccb->ccb_h.status = CAM_REQ_CMP_ERR;
2684                 xpt_done(ccb);
2685                 break;
2686         default:
2687                 panic("%s: Unknown status %d in umass_cam_cb",
2688                         device_get_nameunit(sc->sc_dev), status);
2689         }
2690 }
2691
2692 /* Finalise a completed autosense operation
2693  */
2694 static void
2695 umass_cam_sense_cb(struct umass_softc *sc, void *priv, int residue, int status)
2696 {
2697         union ccb *ccb = (union ccb *) priv;
2698         struct ccb_scsiio *csio = &ccb->csio;           /* deref union */
2699         unsigned char *rcmd;
2700         int rcmdlen;
2701
2702         switch (status) {
2703         case STATUS_CMD_OK:
2704         case STATUS_CMD_UNKNOWN:
2705         case STATUS_CMD_FAILED:
2706                 /* Getting sense data always succeeds (apart from wire
2707                  * failures).
2708                  */
2709                 if ((sc->quirks & RS_NO_CLEAR_UA)
2710                     && csio->cdb_io.cdb_bytes[0] == INQUIRY
2711                     && (csio->sense_data.flags & SSD_KEY)
2712                                                 == SSD_KEY_UNIT_ATTENTION) {
2713                         /* Ignore unit attention errors in the case where
2714                          * the Unit Attention state is not cleared on
2715                          * REQUEST SENSE. They will appear again at the next
2716                          * command.
2717                          */
2718                         ccb->ccb_h.status = CAM_REQ_CMP;
2719                 } else if ((csio->sense_data.flags & SSD_KEY)
2720                                                 == SSD_KEY_NO_SENSE) {
2721                         /* No problem after all (in the case of CBI without
2722                          * CCI)
2723                          */
2724                         ccb->ccb_h.status = CAM_REQ_CMP;
2725                 } else if ((sc->quirks & RS_NO_CLEAR_UA) &&
2726                            (csio->cdb_io.cdb_bytes[0] == READ_CAPACITY) &&
2727                            ((csio->sense_data.flags & SSD_KEY)
2728                             == SSD_KEY_UNIT_ATTENTION)) {
2729                         /*
2730                          * Some devices do not clear the unit attention error
2731                          * on request sense. We insert a test unit ready
2732                          * command to make sure we clear the unit attention
2733                          * condition, then allow the retry to proceed as
2734                          * usual.
2735                          */
2736
2737                         ccb->ccb_h.status = CAM_SCSI_STATUS_ERROR
2738                                             | CAM_AUTOSNS_VALID;
2739                         csio->scsi_status = SCSI_STATUS_CHECK_COND;
2740
2741 #if 0
2742                         DELAY(300000);
2743 #endif
2744
2745                         DPRINTF(UDMASS_SCSI,("%s: Doing a sneaky"
2746                                              "TEST_UNIT_READY\n",
2747                                 device_get_nameunit(sc->sc_dev)));
2748
2749                         /* the rest of the command was filled in at attach */
2750
2751                         rcmd = (unsigned char *) &sc->cam_scsi_command2;
2752                         rcmdlen = sizeof(sc->cam_scsi_command2);
2753
2754                         if (sc->transform(sc,
2755                                         (unsigned char *)
2756                                         &sc->cam_scsi_test_unit_ready,
2757                                         sizeof(sc->cam_scsi_test_unit_ready),
2758                                         &rcmd, &rcmdlen)) {
2759                                 sc->transfer(sc, ccb->ccb_h.target_lun,
2760                                              rcmd, rcmdlen,
2761                                              NULL, 0, DIR_NONE,
2762                                              umass_cam_quirk_cb, (void *) ccb);
2763                         } else {
2764                                 panic("transform(TEST_UNIT_READY) failed");
2765                         }
2766                         break;
2767                 } else {
2768                         ccb->ccb_h.status = CAM_SCSI_STATUS_ERROR
2769                                             | CAM_AUTOSNS_VALID;
2770                         csio->scsi_status = SCSI_STATUS_CHECK_COND;
2771                 }
2772                 xpt_done(ccb);
2773                 break;
2774
2775         default:
2776                 DPRINTF(UDMASS_SCSI, ("%s: Autosense failed, status %d\n",
2777                         device_get_nameunit(sc->sc_dev), status));
2778                 ccb->ccb_h.status = CAM_AUTOSENSE_FAIL;
2779                 xpt_done(ccb);
2780         }
2781 }
2782
2783 /*
2784  * This completion code just handles the fact that we sent a test-unit-ready
2785  * after having previously failed a READ CAPACITY with CHECK_COND.  Even
2786  * though this command succeeded, we have to tell CAM to retry.
2787  */
2788 static void
2789 umass_cam_quirk_cb(struct umass_softc *sc, void *priv, int residue, int status)
2790 {
2791         union ccb *ccb = (union ccb *) priv;
2792
2793         DPRINTF(UDMASS_SCSI, ("%s: Test unit ready returned status %d\n",
2794         device_get_nameunit(sc->sc_dev), status));
2795 #if 0
2796         ccb->ccb_h.status = CAM_REQ_CMP;
2797 #endif
2798         ccb->ccb_h.status = CAM_SCSI_STATUS_ERROR
2799                             | CAM_AUTOSNS_VALID;
2800         ccb->csio.scsi_status = SCSI_STATUS_CHECK_COND;
2801         xpt_done(ccb);
2802 }
2803
2804 static int
2805 umass_driver_load(module_t mod, int what, void *arg)
2806 {
2807         switch (what) {
2808         case MOD_UNLOAD:
2809         case MOD_LOAD:
2810         default:
2811                 return(usbd_driver_load(mod, what, arg));
2812         }
2813 }
2814
2815 /*
2816  * SCSI specific functions
2817  */
2818
2819 static int
2820 umass_scsi_transform(struct umass_softc *sc, unsigned char *cmd, int cmdlen,
2821                      unsigned char **rcmd, int *rcmdlen)
2822 {
2823         switch (cmd[0]) {
2824         case TEST_UNIT_READY:
2825                 if (sc->quirks & NO_TEST_UNIT_READY) {
2826                         KASSERT(*rcmdlen >= sizeof(struct scsi_start_stop_unit),
2827                                 ("rcmdlen = %d < %ld, buffer too small",
2828                                  *rcmdlen,
2829                                  (long)sizeof(struct scsi_start_stop_unit)));
2830                         DPRINTF(UDMASS_SCSI, ("%s: Converted TEST_UNIT_READY "
2831                                 "to START_UNIT\n", device_get_nameunit(sc->sc_dev)));
2832                         memset(*rcmd, 0, *rcmdlen);
2833                         (*rcmd)[0] = START_STOP_UNIT;
2834                         (*rcmd)[4] = SSS_START;
2835                         return 1;
2836                 }
2837                 /* fallthrough */
2838         case INQUIRY:
2839                 /* some drives wedge when asked for full inquiry information. */
2840                 if (sc->quirks & FORCE_SHORT_INQUIRY) {
2841                         memcpy(*rcmd, cmd, cmdlen);
2842                         *rcmdlen = cmdlen;
2843                         (*rcmd)[4] = SHORT_INQUIRY_LENGTH;
2844                         return 1;
2845                 }
2846                 /* fallthrough */
2847         default:
2848                 *rcmd = cmd;            /* We don't need to copy it */
2849                 *rcmdlen = cmdlen;
2850         }
2851
2852         return 1;
2853 }
2854 /* RBC specific functions */
2855 static int
2856 umass_rbc_transform(struct umass_softc *sc, unsigned char *cmd, int cmdlen,
2857                      unsigned char **rcmd, int *rcmdlen)
2858 {
2859         switch (cmd[0]) {
2860         /* these commands are defined in RBC: */
2861         case READ_10:
2862         case READ_CAPACITY:
2863         case START_STOP_UNIT:
2864         case SYNCHRONIZE_CACHE:
2865         case WRITE_10:
2866         case 0x2f: /* VERIFY_10 is absent from scsi_all.h??? */
2867         case INQUIRY:
2868         case MODE_SELECT_10:
2869         case MODE_SENSE_10:
2870         case TEST_UNIT_READY:
2871         case WRITE_BUFFER:
2872          /* The following commands are not listed in my copy of the RBC specs.
2873           * CAM however seems to want those, and at least the Sony DSC device
2874           * appears to support those as well */
2875         case REQUEST_SENSE:
2876         case PREVENT_ALLOW:
2877                 *rcmd = cmd;            /* We don't need to copy it */
2878                 *rcmdlen = cmdlen;
2879                 return 1;
2880         /* All other commands are not legal in RBC */
2881         default:
2882                 kprintf("%s: Unsupported RBC command 0x%02x",
2883                         device_get_nameunit(sc->sc_dev), cmd[0]);
2884                 kprintf("\n");
2885                 return 0;       /* failure */
2886         }
2887 }
2888
2889 /*
2890  * UFI specific functions
2891  */
2892 static int
2893 umass_ufi_transform(struct umass_softc *sc, unsigned char *cmd, int cmdlen,
2894                     unsigned char **rcmd, int *rcmdlen)
2895 {
2896         /* A UFI command is always 12 bytes in length */
2897         KASSERT(*rcmdlen >= UFI_COMMAND_LENGTH,
2898                 ("rcmdlen = %d < %d, buffer too small",
2899                  *rcmdlen, UFI_COMMAND_LENGTH));
2900
2901         *rcmdlen = UFI_COMMAND_LENGTH;
2902         memset(*rcmd, 0, UFI_COMMAND_LENGTH);
2903
2904         switch (cmd[0]) {
2905         /* Commands of which the format has been verified. They should work.
2906          * Copy the command into the (zeroed out) destination buffer.
2907          */
2908         case TEST_UNIT_READY:
2909                 if (sc->quirks &  NO_TEST_UNIT_READY) {
2910                         /* Some devices do not support this command.
2911                          * Start Stop Unit should give the same results
2912                          */
2913                         DPRINTF(UDMASS_UFI, ("%s: Converted TEST_UNIT_READY "
2914                                 "to START_UNIT\n", device_get_nameunit(sc->sc_dev)));
2915                         (*rcmd)[0] = START_STOP_UNIT;
2916                         (*rcmd)[4] = SSS_START;
2917                 } else {
2918                         memcpy(*rcmd, cmd, cmdlen);
2919                 }
2920                 return 1;
2921
2922         case REZERO_UNIT:
2923         case REQUEST_SENSE:
2924         case INQUIRY:
2925         case START_STOP_UNIT:
2926         case SEND_DIAGNOSTIC:
2927         case PREVENT_ALLOW:
2928         case READ_CAPACITY:
2929         case READ_10:
2930         case WRITE_10:
2931         case POSITION_TO_ELEMENT:       /* SEEK_10 */
2932         case MODE_SELECT_10:
2933         case MODE_SENSE_10:
2934         case READ_12:
2935         case WRITE_12:
2936                 memcpy(*rcmd, cmd, cmdlen);
2937                 return 1;
2938
2939         /* Other UFI commands: FORMAT_UNIT, READ_FORMAT_CAPACITY,
2940          * VERIFY, WRITE_AND_VERIFY.
2941          * These should be checked whether they somehow can be made to fit.
2942          */
2943
2944         default:
2945                 kprintf("%s: Unsupported UFI command 0x%02x\n",
2946                         device_get_nameunit(sc->sc_dev), cmd[0]);
2947                 return 0;       /* failure */
2948         }
2949 }
2950
2951 /*
2952  * 8070i (ATAPI) specific functions
2953  */
2954 static int
2955 umass_atapi_transform(struct umass_softc *sc, unsigned char *cmd, int cmdlen,
2956                       unsigned char **rcmd, int *rcmdlen)
2957 {
2958         /* An ATAPI command is always 12 bytes in length. */
2959         KASSERT(*rcmdlen >= ATAPI_COMMAND_LENGTH,
2960                 ("rcmdlen = %d < %d, buffer too small",
2961                  *rcmdlen, ATAPI_COMMAND_LENGTH));
2962
2963         *rcmdlen = ATAPI_COMMAND_LENGTH;
2964         memset(*rcmd, 0, ATAPI_COMMAND_LENGTH);
2965
2966         switch (cmd[0]) {
2967         /* Commands of which the format has been verified. They should work.
2968          * Copy the command into the (zeroed out) destination buffer.
2969          */
2970         case INQUIRY:
2971                 memcpy(*rcmd, cmd, cmdlen);
2972                 /* some drives wedge when asked for full inquiry information. */
2973                 if (sc->quirks & FORCE_SHORT_INQUIRY)
2974                         (*rcmd)[4] = SHORT_INQUIRY_LENGTH;
2975                 return 1;
2976
2977         case TEST_UNIT_READY:
2978                 if (sc->quirks & NO_TEST_UNIT_READY) {
2979                         KASSERT(*rcmdlen >= sizeof(struct scsi_start_stop_unit),
2980                                 ("rcmdlen = %d < %ld, buffer too small",
2981                                  *rcmdlen,
2982                                  (long)sizeof(struct scsi_start_stop_unit)));
2983                         DPRINTF(UDMASS_SCSI, ("%s: Converted TEST_UNIT_READY "
2984                                 "to START_UNIT\n", device_get_nameunit(sc->sc_dev)));
2985                         memset(*rcmd, 0, *rcmdlen);
2986                         (*rcmd)[0] = START_STOP_UNIT;
2987                         (*rcmd)[4] = SSS_START;
2988                         return 1;
2989                 }
2990                 /* fallthrough */
2991         case REZERO_UNIT:
2992         case REQUEST_SENSE:
2993         case START_STOP_UNIT:
2994         case SEND_DIAGNOSTIC:
2995         case PREVENT_ALLOW:
2996         case READ_CAPACITY:
2997         case READ_10:
2998         case WRITE_10:
2999         case POSITION_TO_ELEMENT:       /* SEEK_10 */
3000         case SYNCHRONIZE_CACHE:
3001         case MODE_SELECT_10:
3002         case MODE_SENSE_10:
3003         case READ_BUFFER:
3004         case READ_SUBCHANNEL:
3005         case READ_TOC:
3006         case READ_HEADER:
3007         case PLAY_MSF:
3008         case PLAY_TRACK:
3009         case PLAY_TRACK_REL:
3010         case PAUSE:
3011         case ATAPI_READ_DISK_INFO:
3012         case ATAPI_READ_TRACK_INFO:
3013         case ATAPI_SEND_OPC_INFO:
3014         case ATAPI_READ_MASTER_CUE:
3015         case ATAPI_CLOSE_TRACK:
3016         case ATAPI_READ_BUFFER_CAPACITY:
3017         case ATAPI_SEND_CUE_SHEET:
3018         case ATAPI_BLANK:
3019         case PLAY_12:
3020         case EXCHANGE_MEDIUM:
3021         case READ_DVD_STRUCTURE:
3022         case SET_CD_SPEED:
3023         case 0xe5: /* READ_TRACK_INFO_PHILIPS */
3024                 memcpy(*rcmd, cmd, cmdlen);
3025                 return 1;
3026
3027         case READ_12:
3028         case WRITE_12:
3029         default:
3030                 kprintf("%s: Unsupported ATAPI command 0x%02x\n",
3031                         device_get_nameunit(sc->sc_dev), cmd[0]);
3032                 return 0;       /* failure */
3033         }
3034 }
3035
3036
3037 /* (even the comment is missing) */
3038
3039 DRIVER_MODULE(umass, uhub, umass_driver, umass_devclass, umass_driver_load, 0);
3040
3041
3042
3043 #ifdef USB_DEBUG
3044 static void
3045 umass_bbb_dump_cbw(struct umass_softc *sc, umass_bbb_cbw_t *cbw)
3046 {
3047         int clen = cbw->bCDBLength;
3048         int dlen = UGETDW(cbw->dCBWDataTransferLength);
3049         u_int8_t *c = cbw->CBWCDB;
3050         int tag = UGETDW(cbw->dCBWTag);
3051         int flags = cbw->bCBWFlags;
3052
3053         DPRINTF(UDMASS_BBB, ("%s: CBW %d: cmd = %db "
3054                 "(0x%02x%02x%02x%02x%02x%02x%s), "
3055                 "data = %db, dir = %s\n",
3056                 device_get_nameunit(sc->sc_dev), tag, clen,
3057                 c[0], c[1], c[2], c[3], c[4], c[5], (clen > 6? "...":""),
3058                 dlen, (flags == CBWFLAGS_IN? "in":
3059                        (flags == CBWFLAGS_OUT? "out":"<invalid>"))));
3060 }
3061
3062 static void
3063 umass_bbb_dump_csw(struct umass_softc *sc, umass_bbb_csw_t *csw)
3064 {
3065         int sig = UGETDW(csw->dCSWSignature);
3066         int tag = UGETW(csw->dCSWTag);
3067         int res = UGETDW(csw->dCSWDataResidue);
3068         int status = csw->bCSWStatus;
3069
3070         DPRINTF(UDMASS_BBB, ("%s: CSW %d: sig = 0x%08x (%s), tag = %d, "
3071                 "res = %d, status = 0x%02x (%s)\n", device_get_nameunit(sc->sc_dev),
3072                 tag, sig, (sig == CSWSIGNATURE?  "valid":"invalid"),
3073                 tag, res,
3074                 status, (status == CSWSTATUS_GOOD? "good":
3075                          (status == CSWSTATUS_FAILED? "failed":
3076                           (status == CSWSTATUS_PHASE? "phase":"<invalid>")))));
3077 }
3078
3079 static void
3080 umass_cbi_dump_cmd(struct umass_softc *sc, void *cmd, int cmdlen)
3081 {
3082         u_int8_t *c = cmd;
3083         int dir = sc->transfer_dir;
3084
3085         DPRINTF(UDMASS_BBB, ("%s: cmd = %db "
3086                 "(0x%02x%02x%02x%02x%02x%02x%s), "
3087                 "data = %db, dir = %s\n",
3088                 device_get_nameunit(sc->sc_dev), cmdlen,
3089                 c[0], c[1], c[2], c[3], c[4], c[5], (cmdlen > 6? "...":""),
3090                 sc->transfer_datalen,
3091                 (dir == DIR_IN? "in":
3092                  (dir == DIR_OUT? "out":
3093                   (dir == DIR_NONE? "no data phase": "<invalid>")))));
3094 }
3095
3096 static void
3097 umass_dump_buffer(struct umass_softc *sc, u_int8_t *buffer, int buflen,
3098                   int printlen)
3099 {
3100         int i, j;
3101         char s1[40];
3102         char s2[40];
3103         char s3[5];
3104
3105         s1[0] = '\0';
3106         s3[0] = '\0';
3107
3108         ksprintf(s2, " buffer=%p, buflen=%d", buffer, buflen);
3109         for (i = 0; i < buflen && i < printlen; i++) {
3110                 j = i % 16;
3111                 if (j == 0 && i != 0) {
3112                         DPRINTF(UDMASS_GEN, ("%s: 0x %s%s\n",
3113                                 device_get_nameunit(sc->sc_dev), s1, s2));
3114                         s2[0] = '\0';
3115                 }
3116                 ksprintf(&s1[j*2], "%02x", buffer[i] & 0xff);
3117         }
3118         if (buflen > printlen)
3119                 ksprintf(s3, " ...");
3120         DPRINTF(UDMASS_GEN, ("%s: 0x %s%s%s\n",
3121                 device_get_nameunit(sc->sc_dev), s1, s2, s3));
3122 }
3123 #endif