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