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