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