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