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