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