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