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