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