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