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