source: rtems-libbsd/freebsd/sys/dev/usb/storage/umass.c @ 8e65e1b

55-freebsd-126-freebsd-12freebsd-9.3
Last change on this file since 8e65e1b was 8e65e1b, checked in by Sebastian Huber <sebastian.huber@…>, on 08/23/16 at 13:51:45

usb: Update to FreeBSD trunk 2016-08-23

FreeBSD trunk, 2016-08-23, 9fe7c416e6abb28b1398fd3e5687099846800cfd.

  • Property mode set to 100644
File size: 79.8 KB
Line 
1#include <machine/rtems-bsd-kernel-space.h>
2
3#include <sys/cdefs.h>
4__FBSDID("$FreeBSD$");
5
6/*-
7 * Copyright (c) 1999 MAEKAWA Masahide <bishop@rr.iij4u.or.jp>,
8 *                    Nick Hibma <n_hibma@FreeBSD.org>
9 * All rights reserved.
10 *
11 * Redistribution and use in source and binary forms, with or without
12 * modification, are permitted provided that the following conditions
13 * are met:
14 * 1. Redistributions of source code must retain the above copyright
15 *    notice, this list of conditions and the following disclaimer.
16 * 2. Redistributions in binary form must reproduce the above copyright
17 *    notice, this list of conditions and the following disclaimer in the
18 *    documentation and/or other materials provided with the distribution.
19 *
20 * THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND
21 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
22 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
23 * ARE DISCLAIMED.  IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE
24 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
25 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
26 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
27 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
28 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
29 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
30 * SUCH DAMAGE.
31 *
32 *      $FreeBSD$
33 *      $NetBSD: umass.c,v 1.28 2000/04/02 23:46:53 augustss Exp $
34 */
35
36/* Also already merged from NetBSD:
37 *      $NetBSD: umass.c,v 1.67 2001/11/25 19:05:22 augustss Exp $
38 *      $NetBSD: umass.c,v 1.90 2002/11/04 19:17:33 pooka Exp $
39 *      $NetBSD: umass.c,v 1.108 2003/11/07 17:03:25 wiz Exp $
40 *      $NetBSD: umass.c,v 1.109 2003/12/04 13:57:31 keihan Exp $
41 */
42
43/*
44 * Universal Serial Bus Mass Storage Class specs:
45 * http://www.usb.org/developers/devclass_docs/usb_msc_overview_1.2.pdf
46 * http://www.usb.org/developers/devclass_docs/usbmassbulk_10.pdf
47 * http://www.usb.org/developers/devclass_docs/usb_msc_cbi_1.1.pdf
48 * http://www.usb.org/developers/devclass_docs/usbmass-ufi10.pdf
49 */
50
51/*
52 * Ported to NetBSD by Lennart Augustsson <augustss@NetBSD.org>.
53 * Parts of the code written by Jason R. Thorpe <thorpej@shagadelic.org>.
54 */
55
56/*
57 * The driver handles 3 Wire Protocols
58 * - Command/Bulk/Interrupt (CBI)
59 * - Command/Bulk/Interrupt with Command Completion Interrupt (CBI with CCI)
60 * - Mass Storage Bulk-Only (BBB)
61 *   (BBB refers Bulk/Bulk/Bulk for Command/Data/Status phases)
62 *
63 * Over these wire protocols it handles the following command protocols
64 * - SCSI
65 * - UFI (floppy command set)
66 * - 8070i (ATAPI)
67 *
68 * UFI and 8070i (ATAPI) are transformed versions of the SCSI command set. The
69 * sc->sc_transform method is used to convert the commands into the appropriate
70 * format (if at all necessary). For example, UFI requires all commands to be
71 * 12 bytes in length amongst other things.
72 *
73 * The source code below is marked and can be split into a number of pieces
74 * (in this order):
75 *
76 * - probe/attach/detach
77 * - generic transfer routines
78 * - BBB
79 * - CBI
80 * - CBI_I (in addition to functions from CBI)
81 * - CAM (Common Access Method)
82 * - SCSI
83 * - UFI
84 * - 8070i (ATAPI)
85 *
86 * The protocols are implemented using a state machine, for the transfers as
87 * well as for the resets. The state machine is contained in umass_t_*_callback.
88 * The state machine is started through either umass_command_start() or
89 * umass_reset().
90 *
91 * The reason for doing this is a) CAM performs a lot better this way and b) it
92 * avoids using tsleep from interrupt context (for example after a failed
93 * transfer).
94 */
95
96/*
97 * The SCSI related part of this driver has been derived from the
98 * dev/ppbus/vpo.c driver, by Nicolas Souchu (nsouch@FreeBSD.org).
99 *
100 * The CAM layer uses so called actions which are messages sent to the host
101 * adapter for completion. The actions come in through umass_cam_action. The
102 * appropriate block of routines is called depending on the transport protocol
103 * in use. When the transfer has finished, these routines call
104 * umass_cam_cb again to complete the CAM command.
105 */
106
107#include <sys/stdint.h>
108#include <sys/stddef.h>
109#include <rtems/bsd/sys/param.h>
110#include <sys/queue.h>
111#include <sys/types.h>
112#include <sys/systm.h>
113#include <sys/kernel.h>
114#include <sys/bus.h>
115#include <sys/module.h>
116#include <rtems/bsd/sys/lock.h>
117#include <sys/mutex.h>
118#include <sys/condvar.h>
119#include <sys/sysctl.h>
120#include <sys/sx.h>
121#include <rtems/bsd/sys/unistd.h>
122#include <sys/callout.h>
123#include <sys/malloc.h>
124#include <sys/priv.h>
125
126#include <dev/usb/usb.h>
127#include <dev/usb/usbdi.h>
128#include <dev/usb/usbdi_util.h>
129#include <rtems/bsd/local/usbdevs.h>
130
131#include <dev/usb/quirk/usb_quirk.h>
132
133#include <cam/cam.h>
134#include <cam/cam_ccb.h>
135#include <cam/cam_sim.h>
136#include <cam/cam_xpt_sim.h>
137#include <cam/scsi/scsi_all.h>
138#include <cam/scsi/scsi_da.h>
139
140#include <cam/cam_periph.h>
141
142#ifdef USB_DEBUG
143#define DIF(m, x)                               \
144  do {                                          \
145    if (umass_debug & (m)) { x ; }              \
146  } while (0)
147
148#define DPRINTF(sc, m, fmt, ...)                        \
149  do {                                                  \
150    if (umass_debug & (m)) {                            \
151        printf("%s:%s: " fmt,                           \
152               (sc) ? (const char *)(sc)->sc_name :     \
153               (const char *)"umassX",                  \
154                __FUNCTION__ ,## __VA_ARGS__);          \
155    }                                                   \
156  } while (0)
157
158#define UDMASS_GEN      0x00010000      /* general */
159#define UDMASS_SCSI     0x00020000      /* scsi */
160#define UDMASS_UFI      0x00040000      /* ufi command set */
161#define UDMASS_ATAPI    0x00080000      /* 8070i command set */
162#define UDMASS_CMD      (UDMASS_SCSI|UDMASS_UFI|UDMASS_ATAPI)
163#define UDMASS_USB      0x00100000      /* USB general */
164#define UDMASS_BBB      0x00200000      /* Bulk-Only transfers */
165#define UDMASS_CBI      0x00400000      /* CBI transfers */
166#define UDMASS_WIRE     (UDMASS_BBB|UDMASS_CBI)
167#define UDMASS_ALL      0xffff0000      /* all of the above */
168static int umass_debug;
169static int umass_throttle;
170
171static SYSCTL_NODE(_hw_usb, OID_AUTO, umass, CTLFLAG_RW, 0, "USB umass");
172SYSCTL_INT(_hw_usb_umass, OID_AUTO, debug, CTLFLAG_RWTUN,
173    &umass_debug, 0, "umass debug level");
174SYSCTL_INT(_hw_usb_umass, OID_AUTO, throttle, CTLFLAG_RWTUN,
175    &umass_throttle, 0, "Forced delay between commands in milliseconds");
176#else
177#define DIF(...) do { } while (0)
178#define DPRINTF(...) do { } while (0)
179#endif
180
181#define UMASS_BULK_SIZE (1 << 17)
182#define UMASS_CBI_DIAGNOSTIC_CMDLEN 12  /* bytes */
183#define UMASS_MAX_CMDLEN MAX(12, CAM_MAX_CDBLEN)        /* bytes */
184
185/* USB transfer definitions */
186
187#define UMASS_T_BBB_RESET1      0       /* Bulk-Only */
188#define UMASS_T_BBB_RESET2      1
189#define UMASS_T_BBB_RESET3      2
190#define UMASS_T_BBB_COMMAND     3
191#define UMASS_T_BBB_DATA_READ   4
192#define UMASS_T_BBB_DATA_RD_CS  5
193#define UMASS_T_BBB_DATA_WRITE  6
194#define UMASS_T_BBB_DATA_WR_CS  7
195#define UMASS_T_BBB_STATUS      8
196#define UMASS_T_BBB_MAX         9
197
198#define UMASS_T_CBI_RESET1      0       /* CBI */
199#define UMASS_T_CBI_RESET2      1
200#define UMASS_T_CBI_RESET3      2
201#define UMASS_T_CBI_COMMAND     3
202#define UMASS_T_CBI_DATA_READ   4
203#define UMASS_T_CBI_DATA_RD_CS  5
204#define UMASS_T_CBI_DATA_WRITE  6
205#define UMASS_T_CBI_DATA_WR_CS  7
206#define UMASS_T_CBI_STATUS      8
207#define UMASS_T_CBI_RESET4      9
208#define UMASS_T_CBI_MAX        10
209
210#define UMASS_T_MAX MAX(UMASS_T_CBI_MAX, UMASS_T_BBB_MAX)
211
212/* Generic definitions */
213
214/* Direction for transfer */
215#define DIR_NONE        0
216#define DIR_IN          1
217#define DIR_OUT         2
218
219/* device name */
220#define DEVNAME         "umass"
221#define DEVNAME_SIM     "umass-sim"
222
223/* Approximate maximum transfer speeds (assumes 33% overhead). */
224#define UMASS_FULL_TRANSFER_SPEED       1000
225#define UMASS_HIGH_TRANSFER_SPEED       40000
226#define UMASS_SUPER_TRANSFER_SPEED      400000
227#define UMASS_FLOPPY_TRANSFER_SPEED     20
228
229#define UMASS_TIMEOUT                   5000    /* ms */
230
231/* CAM specific definitions */
232
233#define UMASS_SCSIID_MAX        1       /* maximum number of drives expected */
234#define UMASS_SCSIID_HOST       UMASS_SCSIID_MAX
235
236/* Bulk-Only features */
237
238#define UR_BBB_RESET            0xff    /* Bulk-Only reset */
239#define UR_BBB_GET_MAX_LUN      0xfe    /* Get maximum lun */
240
241/* Command Block Wrapper */
242typedef struct {
243        uDWord  dCBWSignature;
244#define CBWSIGNATURE    0x43425355
245        uDWord  dCBWTag;
246        uDWord  dCBWDataTransferLength;
247        uByte   bCBWFlags;
248#define CBWFLAGS_OUT    0x00
249#define CBWFLAGS_IN     0x80
250        uByte   bCBWLUN;
251        uByte   bCDBLength;
252#define CBWCDBLENGTH    16
253        uByte   CBWCDB[CBWCDBLENGTH];
254} __packed umass_bbb_cbw_t;
255
256#define UMASS_BBB_CBW_SIZE      31
257
258/* Command Status Wrapper */
259typedef struct {
260        uDWord  dCSWSignature;
261#define CSWSIGNATURE    0x53425355
262#define CSWSIGNATURE_IMAGINATION_DBX1   0x43425355
263#define CSWSIGNATURE_OLYMPUS_C1 0x55425355
264        uDWord  dCSWTag;
265        uDWord  dCSWDataResidue;
266        uByte   bCSWStatus;
267#define CSWSTATUS_GOOD  0x0
268#define CSWSTATUS_FAILED        0x1
269#define CSWSTATUS_PHASE 0x2
270} __packed umass_bbb_csw_t;
271
272#define UMASS_BBB_CSW_SIZE      13
273
274/* CBI features */
275
276#define UR_CBI_ADSC     0x00
277
278typedef union {
279        struct {
280                uint8_t type;
281#define IDB_TYPE_CCI            0x00
282                uint8_t value;
283#define IDB_VALUE_PASS          0x00
284#define IDB_VALUE_FAIL          0x01
285#define IDB_VALUE_PHASE         0x02
286#define IDB_VALUE_PERSISTENT    0x03
287#define IDB_VALUE_STATUS_MASK   0x03
288        } __packed common;
289
290        struct {
291                uint8_t asc;
292                uint8_t ascq;
293        } __packed ufi;
294} __packed umass_cbi_sbl_t;
295
296struct umass_softc;                     /* see below */
297
298typedef void (umass_callback_t)(struct umass_softc *sc, union ccb *ccb,
299        uint32_t residue, uint8_t status);
300
301#define STATUS_CMD_OK           0       /* everything ok */
302#define STATUS_CMD_UNKNOWN      1       /* will have to fetch sense */
303#define STATUS_CMD_FAILED       2       /* transfer was ok, command failed */
304#define STATUS_WIRE_FAILED      3       /* couldn't even get command across */
305
306typedef uint8_t (umass_transform_t)(struct umass_softc *sc, uint8_t *cmd_ptr,
307        uint8_t cmd_len);
308
309/* Wire and command protocol */
310#define UMASS_PROTO_BBB         0x0001  /* USB wire protocol */
311#define UMASS_PROTO_CBI         0x0002
312#define UMASS_PROTO_CBI_I       0x0004
313#define UMASS_PROTO_WIRE        0x00ff  /* USB wire protocol mask */
314#define UMASS_PROTO_SCSI        0x0100  /* command protocol */
315#define UMASS_PROTO_ATAPI       0x0200
316#define UMASS_PROTO_UFI         0x0400
317#define UMASS_PROTO_RBC         0x0800
318#define UMASS_PROTO_COMMAND     0xff00  /* command protocol mask */
319
320/* Device specific quirks */
321#define NO_QUIRKS               0x0000
322        /*
323         * The drive does not support Test Unit Ready. Convert to Start Unit
324         */
325#define NO_TEST_UNIT_READY      0x0001
326        /*
327         * The drive does not reset the Unit Attention state after REQUEST
328         * SENSE has been sent. The INQUIRY command does not reset the UA
329         * either, and so CAM runs in circles trying to retrieve the initial
330         * INQUIRY data.
331         */
332#define RS_NO_CLEAR_UA          0x0002
333        /* The drive does not support START STOP.  */
334#define NO_START_STOP           0x0004
335        /* Don't ask for full inquiry data (255b).  */
336#define FORCE_SHORT_INQUIRY     0x0008
337        /* Needs to be initialised the Shuttle way */
338#define SHUTTLE_INIT            0x0010
339        /* Drive needs to be switched to alternate iface 1 */
340#define ALT_IFACE_1             0x0020
341        /* Drive does not do 1Mb/s, but just floppy speeds (20kb/s) */
342#define FLOPPY_SPEED            0x0040
343        /* The device can't count and gets the residue of transfers wrong */
344#define IGNORE_RESIDUE          0x0080
345        /* No GetMaxLun call */
346#define NO_GETMAXLUN            0x0100
347        /* The device uses a weird CSWSIGNATURE. */
348#define WRONG_CSWSIG            0x0200
349        /* Device cannot handle INQUIRY so fake a generic response */
350#define NO_INQUIRY              0x0400
351        /* Device cannot handle INQUIRY EVPD, return CHECK CONDITION */
352#define NO_INQUIRY_EVPD         0x0800
353        /* Pad all RBC requests to 12 bytes. */
354#define RBC_PAD_TO_12           0x1000
355        /*
356         * Device reports number of sectors from READ_CAPACITY, not max
357         * sector number.
358         */
359#define READ_CAPACITY_OFFBY1    0x2000
360        /*
361         * Device cannot handle a SCSI synchronize cache command.  Normally
362         * this quirk would be handled in the cam layer, but for IDE bridges
363         * we need to associate the quirk with the bridge and not the
364         * underlying disk device.  This is handled by faking a success
365         * result.
366         */
367#define NO_SYNCHRONIZE_CACHE    0x4000
368        /* Device does not support 'PREVENT/ALLOW MEDIUM REMOVAL'. */
369#define NO_PREVENT_ALLOW        0x8000
370
371struct umass_softc {
372
373        struct scsi_sense cam_scsi_sense;
374        struct scsi_test_unit_ready cam_scsi_test_unit_ready;
375        struct mtx sc_mtx;
376        struct {
377                uint8_t *data_ptr;
378                union ccb *ccb;
379                umass_callback_t *callback;
380
381                uint32_t data_len;      /* bytes */
382                uint32_t data_rem;      /* bytes */
383                uint32_t data_timeout;  /* ms */
384                uint32_t actlen;        /* bytes */
385
386                uint8_t cmd_data[UMASS_MAX_CMDLEN];
387                uint8_t cmd_len;        /* bytes */
388                uint8_t dir;
389                uint8_t lun;
390        }       sc_transfer;
391
392        /* Bulk specific variables for transfers in progress */
393        umass_bbb_cbw_t cbw;            /* command block wrapper */
394        umass_bbb_csw_t csw;            /* command status wrapper */
395
396        /* CBI specific variables for transfers in progress */
397        umass_cbi_sbl_t sbl;            /* status block */
398
399        device_t sc_dev;
400        struct usb_device *sc_udev;
401        struct cam_sim *sc_sim;         /* SCSI Interface Module */
402        struct usb_xfer *sc_xfer[UMASS_T_MAX];
403
404        /*
405         * The command transform function is used to convert the SCSI
406         * commands into their derivatives, like UFI, ATAPI, and friends.
407         */
408        umass_transform_t *sc_transform;
409
410        uint32_t sc_unit;
411        uint32_t sc_quirks;             /* they got it almost right */
412        uint32_t sc_proto;              /* wire and cmd protocol */
413
414        uint8_t sc_name[16];
415        uint8_t sc_iface_no;            /* interface number */
416        uint8_t sc_maxlun;              /* maximum LUN number, inclusive */
417        uint8_t sc_last_xfer_index;
418        uint8_t sc_status_try;
419};
420
421struct umass_probe_proto {
422        uint32_t quirks;
423        uint32_t proto;
424
425        int     error;
426};
427
428/* prototypes */
429
430static device_probe_t umass_probe;
431static device_attach_t umass_attach;
432static device_detach_t umass_detach;
433
434static usb_callback_t umass_tr_error;
435static usb_callback_t umass_t_bbb_reset1_callback;
436static usb_callback_t umass_t_bbb_reset2_callback;
437static usb_callback_t umass_t_bbb_reset3_callback;
438static usb_callback_t umass_t_bbb_command_callback;
439static usb_callback_t umass_t_bbb_data_read_callback;
440static usb_callback_t umass_t_bbb_data_rd_cs_callback;
441static usb_callback_t umass_t_bbb_data_write_callback;
442static usb_callback_t umass_t_bbb_data_wr_cs_callback;
443static usb_callback_t umass_t_bbb_status_callback;
444static usb_callback_t umass_t_cbi_reset1_callback;
445static usb_callback_t umass_t_cbi_reset2_callback;
446static usb_callback_t umass_t_cbi_reset3_callback;
447static usb_callback_t umass_t_cbi_reset4_callback;
448static usb_callback_t umass_t_cbi_command_callback;
449static usb_callback_t umass_t_cbi_data_read_callback;
450static usb_callback_t umass_t_cbi_data_rd_cs_callback;
451static usb_callback_t umass_t_cbi_data_write_callback;
452static usb_callback_t umass_t_cbi_data_wr_cs_callback;
453static usb_callback_t umass_t_cbi_status_callback;
454
455static void     umass_cancel_ccb(struct umass_softc *);
456static void     umass_init_shuttle(struct umass_softc *);
457static void     umass_reset(struct umass_softc *);
458static void     umass_t_bbb_data_clear_stall_callback(struct usb_xfer *,
459                    uint8_t, uint8_t, usb_error_t);
460static void     umass_command_start(struct umass_softc *, uint8_t, void *,
461                    uint32_t, uint32_t, umass_callback_t *, union ccb *);
462static uint8_t  umass_bbb_get_max_lun(struct umass_softc *);
463static void     umass_cbi_start_status(struct umass_softc *);
464static void     umass_t_cbi_data_clear_stall_callback(struct usb_xfer *,
465                    uint8_t, uint8_t, usb_error_t);
466static int      umass_cam_attach_sim(struct umass_softc *);
467#ifndef __rtems__
468static void     umass_cam_attach(struct umass_softc *);
469#endif /* __rtems__ */
470static void     umass_cam_detach_sim(struct umass_softc *);
471static void     umass_cam_action(struct cam_sim *, union ccb *);
472static void     umass_cam_poll(struct cam_sim *);
473static void     umass_cam_cb(struct umass_softc *, union ccb *, uint32_t,
474                    uint8_t);
475static void     umass_cam_sense_cb(struct umass_softc *, union ccb *, uint32_t,
476                    uint8_t);
477static void     umass_cam_quirk_cb(struct umass_softc *, union ccb *, uint32_t,
478                    uint8_t);
479static uint8_t  umass_scsi_transform(struct umass_softc *, uint8_t *, uint8_t);
480static uint8_t  umass_rbc_transform(struct umass_softc *, uint8_t *, uint8_t);
481static uint8_t  umass_ufi_transform(struct umass_softc *, uint8_t *, uint8_t);
482static uint8_t  umass_atapi_transform(struct umass_softc *, uint8_t *,
483                    uint8_t);
484static uint8_t  umass_no_transform(struct umass_softc *, uint8_t *, uint8_t);
485static uint8_t  umass_std_transform(struct umass_softc *, union ccb *, uint8_t
486                    *, uint8_t);
487
488#ifdef USB_DEBUG
489static void     umass_bbb_dump_cbw(struct umass_softc *, umass_bbb_cbw_t *);
490static void     umass_bbb_dump_csw(struct umass_softc *, umass_bbb_csw_t *);
491static void     umass_cbi_dump_cmd(struct umass_softc *, void *, uint8_t);
492static void     umass_dump_buffer(struct umass_softc *, uint8_t *, uint32_t,
493                    uint32_t);
494#endif
495
496static struct usb_config umass_bbb_config[UMASS_T_BBB_MAX] = {
497
498        [UMASS_T_BBB_RESET1] = {
499                .type = UE_CONTROL,
500                .endpoint = 0x00,       /* Control pipe */
501                .direction = UE_DIR_ANY,
502                .bufsize = sizeof(struct usb_device_request),
503                .callback = &umass_t_bbb_reset1_callback,
504                .timeout = 5000,        /* 5 seconds */
505                .interval = 500,        /* 500 milliseconds */
506        },
507
508        [UMASS_T_BBB_RESET2] = {
509                .type = UE_CONTROL,
510                .endpoint = 0x00,       /* Control pipe */
511                .direction = UE_DIR_ANY,
512                .bufsize = sizeof(struct usb_device_request),
513                .callback = &umass_t_bbb_reset2_callback,
514                .timeout = 5000,        /* 5 seconds */
515                .interval = 50, /* 50 milliseconds */
516        },
517
518        [UMASS_T_BBB_RESET3] = {
519                .type = UE_CONTROL,
520                .endpoint = 0x00,       /* Control pipe */
521                .direction = UE_DIR_ANY,
522                .bufsize = sizeof(struct usb_device_request),
523                .callback = &umass_t_bbb_reset3_callback,
524                .timeout = 5000,        /* 5 seconds */
525                .interval = 50, /* 50 milliseconds */
526        },
527
528        [UMASS_T_BBB_COMMAND] = {
529                .type = UE_BULK,
530                .endpoint = UE_ADDR_ANY,
531                .direction = UE_DIR_OUT,
532                .bufsize = sizeof(umass_bbb_cbw_t),
533                .callback = &umass_t_bbb_command_callback,
534                .timeout = 5000,        /* 5 seconds */
535        },
536
537        [UMASS_T_BBB_DATA_READ] = {
538                .type = UE_BULK,
539                .endpoint = UE_ADDR_ANY,
540                .direction = UE_DIR_IN,
541                .bufsize = UMASS_BULK_SIZE,
542                .flags = {.proxy_buffer = 1,.short_xfer_ok = 1,.ext_buffer=1,},
543                .callback = &umass_t_bbb_data_read_callback,
544                .timeout = 0,   /* overwritten later */
545        },
546
547        [UMASS_T_BBB_DATA_RD_CS] = {
548                .type = UE_CONTROL,
549                .endpoint = 0x00,       /* Control pipe */
550                .direction = UE_DIR_ANY,
551                .bufsize = sizeof(struct usb_device_request),
552                .callback = &umass_t_bbb_data_rd_cs_callback,
553                .timeout = 5000,        /* 5 seconds */
554        },
555
556        [UMASS_T_BBB_DATA_WRITE] = {
557                .type = UE_BULK,
558                .endpoint = UE_ADDR_ANY,
559                .direction = UE_DIR_OUT,
560                .bufsize = UMASS_BULK_SIZE,
561                .flags = {.proxy_buffer = 1,.short_xfer_ok = 1,.ext_buffer=1,},
562                .callback = &umass_t_bbb_data_write_callback,
563                .timeout = 0,   /* overwritten later */
564        },
565
566        [UMASS_T_BBB_DATA_WR_CS] = {
567                .type = UE_CONTROL,
568                .endpoint = 0x00,       /* Control pipe */
569                .direction = UE_DIR_ANY,
570                .bufsize = sizeof(struct usb_device_request),
571                .callback = &umass_t_bbb_data_wr_cs_callback,
572                .timeout = 5000,        /* 5 seconds */
573        },
574
575        [UMASS_T_BBB_STATUS] = {
576                .type = UE_BULK,
577                .endpoint = UE_ADDR_ANY,
578                .direction = UE_DIR_IN,
579                .bufsize = sizeof(umass_bbb_csw_t),
580                .flags = {.short_xfer_ok = 1,},
581                .callback = &umass_t_bbb_status_callback,
582                .timeout = 5000,        /* ms */
583        },
584};
585
586static struct usb_config umass_cbi_config[UMASS_T_CBI_MAX] = {
587
588        [UMASS_T_CBI_RESET1] = {
589                .type = UE_CONTROL,
590                .endpoint = 0x00,       /* Control pipe */
591                .direction = UE_DIR_ANY,
592                .bufsize = (sizeof(struct usb_device_request) +
593                    UMASS_CBI_DIAGNOSTIC_CMDLEN),
594                .callback = &umass_t_cbi_reset1_callback,
595                .timeout = 5000,        /* 5 seconds */
596                .interval = 500,        /* 500 milliseconds */
597        },
598
599        [UMASS_T_CBI_RESET2] = {
600                .type = UE_CONTROL,
601                .endpoint = 0x00,       /* Control pipe */
602                .direction = UE_DIR_ANY,
603                .bufsize = sizeof(struct usb_device_request),
604                .callback = &umass_t_cbi_reset2_callback,
605                .timeout = 5000,        /* 5 seconds */
606                .interval = 50, /* 50 milliseconds */
607        },
608
609        [UMASS_T_CBI_RESET3] = {
610                .type = UE_CONTROL,
611                .endpoint = 0x00,       /* Control pipe */
612                .direction = UE_DIR_ANY,
613                .bufsize = sizeof(struct usb_device_request),
614                .callback = &umass_t_cbi_reset3_callback,
615                .timeout = 5000,        /* 5 seconds */
616                .interval = 50, /* 50 milliseconds */
617        },
618
619        [UMASS_T_CBI_COMMAND] = {
620                .type = UE_CONTROL,
621                .endpoint = 0x00,       /* Control pipe */
622                .direction = UE_DIR_ANY,
623                .bufsize = (sizeof(struct usb_device_request) +
624                    UMASS_MAX_CMDLEN),
625                .callback = &umass_t_cbi_command_callback,
626                .timeout = 5000,        /* 5 seconds */
627        },
628
629        [UMASS_T_CBI_DATA_READ] = {
630                .type = UE_BULK,
631                .endpoint = UE_ADDR_ANY,
632                .direction = UE_DIR_IN,
633                .bufsize = UMASS_BULK_SIZE,
634                .flags = {.proxy_buffer = 1,.short_xfer_ok = 1,.ext_buffer=1,},
635                .callback = &umass_t_cbi_data_read_callback,
636                .timeout = 0,   /* overwritten later */
637        },
638
639        [UMASS_T_CBI_DATA_RD_CS] = {
640                .type = UE_CONTROL,
641                .endpoint = 0x00,       /* Control pipe */
642                .direction = UE_DIR_ANY,
643                .bufsize = sizeof(struct usb_device_request),
644                .callback = &umass_t_cbi_data_rd_cs_callback,
645                .timeout = 5000,        /* 5 seconds */
646        },
647
648        [UMASS_T_CBI_DATA_WRITE] = {
649                .type = UE_BULK,
650                .endpoint = UE_ADDR_ANY,
651                .direction = UE_DIR_OUT,
652                .bufsize = UMASS_BULK_SIZE,
653                .flags = {.proxy_buffer = 1,.short_xfer_ok = 1,.ext_buffer=1,},
654                .callback = &umass_t_cbi_data_write_callback,
655                .timeout = 0,   /* overwritten later */
656        },
657
658        [UMASS_T_CBI_DATA_WR_CS] = {
659                .type = UE_CONTROL,
660                .endpoint = 0x00,       /* Control pipe */
661                .direction = UE_DIR_ANY,
662                .bufsize = sizeof(struct usb_device_request),
663                .callback = &umass_t_cbi_data_wr_cs_callback,
664                .timeout = 5000,        /* 5 seconds */
665        },
666
667        [UMASS_T_CBI_STATUS] = {
668                .type = UE_INTERRUPT,
669                .endpoint = UE_ADDR_ANY,
670                .direction = UE_DIR_IN,
671                .flags = {.short_xfer_ok = 1,.no_pipe_ok = 1,},
672                .bufsize = sizeof(umass_cbi_sbl_t),
673                .callback = &umass_t_cbi_status_callback,
674                .timeout = 5000,        /* ms */
675        },
676
677        [UMASS_T_CBI_RESET4] = {
678                .type = UE_CONTROL,
679                .endpoint = 0x00,       /* Control pipe */
680                .direction = UE_DIR_ANY,
681                .bufsize = sizeof(struct usb_device_request),
682                .callback = &umass_t_cbi_reset4_callback,
683                .timeout = 5000,        /* ms */
684        },
685};
686
687/* If device cannot return valid inquiry data, fake it */
688static const uint8_t fake_inq_data[SHORT_INQUIRY_LENGTH] = {
689        0, /* removable */ 0x80, SCSI_REV_2, SCSI_REV_2,
690         /* additional_length */ 31, 0, 0, 0
691};
692
693#define UFI_COMMAND_LENGTH      12      /* UFI commands are always 12 bytes */
694#define ATAPI_COMMAND_LENGTH    12      /* ATAPI commands are always 12 bytes */
695
696static devclass_t umass_devclass;
697
698static device_method_t umass_methods[] = {
699        /* Device interface */
700        DEVMETHOD(device_probe, umass_probe),
701        DEVMETHOD(device_attach, umass_attach),
702        DEVMETHOD(device_detach, umass_detach),
703
704        DEVMETHOD_END
705};
706
707static driver_t umass_driver = {
708        .name = "umass",
709        .methods = umass_methods,
710        .size = sizeof(struct umass_softc),
711};
712
713static const STRUCT_USB_HOST_ID __used umass_devs[] = {
714        /* generic mass storage class */
715        {USB_IFACE_CLASS(UICLASS_MASS),},
716};
717
718DRIVER_MODULE(umass, uhub, umass_driver, umass_devclass, NULL, 0);
719MODULE_DEPEND(umass, usb, 1, 1, 1);
720MODULE_DEPEND(umass, cam, 1, 1, 1);
721MODULE_VERSION(umass, 1);
722#ifndef __rtems__
723USB_PNP_HOST_INFO(umass_devs);
724#endif /* __rtems__ */
725
726/*
727 * USB device probe/attach/detach
728 */
729
730static uint16_t
731umass_get_proto(struct usb_interface *iface)
732{
733        struct usb_interface_descriptor *id;
734        uint16_t retval;
735
736        retval = 0;
737
738        /* Check for a standards compliant device */
739        id = usbd_get_interface_descriptor(iface);
740        if ((id == NULL) ||
741            (id->bInterfaceClass != UICLASS_MASS)) {
742                goto done;
743        }
744        switch (id->bInterfaceSubClass) {
745        case UISUBCLASS_SCSI:
746                retval |= UMASS_PROTO_SCSI;
747                break;
748        case UISUBCLASS_UFI:
749                retval |= UMASS_PROTO_UFI;
750                break;
751        case UISUBCLASS_RBC:
752                retval |= UMASS_PROTO_RBC;
753                break;
754        case UISUBCLASS_SFF8020I:
755        case UISUBCLASS_SFF8070I:
756                retval |= UMASS_PROTO_ATAPI;
757                break;
758        default:
759                goto done;
760        }
761
762        switch (id->bInterfaceProtocol) {
763        case UIPROTO_MASS_CBI:
764                retval |= UMASS_PROTO_CBI;
765                break;
766        case UIPROTO_MASS_CBI_I:
767                retval |= UMASS_PROTO_CBI_I;
768                break;
769        case UIPROTO_MASS_BBB_OLD:
770        case UIPROTO_MASS_BBB:
771                retval |= UMASS_PROTO_BBB;
772                break;
773        default:
774                goto done;
775        }
776done:
777        return (retval);
778}
779
780/*
781 * Match the device we are seeing with the devices supported.
782 */
783static struct umass_probe_proto
784umass_probe_proto(device_t dev, struct usb_attach_arg *uaa)
785{
786        struct umass_probe_proto ret;
787        uint32_t quirks = NO_QUIRKS;
788        uint32_t proto = umass_get_proto(uaa->iface);
789
790        memset(&ret, 0, sizeof(ret));
791        ret.error = BUS_PROBE_GENERIC;
792
793        /* Search for protocol enforcement */
794
795        if (usb_test_quirk(uaa, UQ_MSC_FORCE_WIRE_BBB)) {
796                proto &= ~UMASS_PROTO_WIRE;
797                proto |= UMASS_PROTO_BBB;
798        } else if (usb_test_quirk(uaa, UQ_MSC_FORCE_WIRE_CBI)) {
799                proto &= ~UMASS_PROTO_WIRE;
800                proto |= UMASS_PROTO_CBI;
801        } else if (usb_test_quirk(uaa, UQ_MSC_FORCE_WIRE_CBI_I)) {
802                proto &= ~UMASS_PROTO_WIRE;
803                proto |= UMASS_PROTO_CBI_I;
804        }
805
806        if (usb_test_quirk(uaa, UQ_MSC_FORCE_PROTO_SCSI)) {
807                proto &= ~UMASS_PROTO_COMMAND;
808                proto |= UMASS_PROTO_SCSI;
809        } else if (usb_test_quirk(uaa, UQ_MSC_FORCE_PROTO_ATAPI)) {
810                proto &= ~UMASS_PROTO_COMMAND;
811                proto |= UMASS_PROTO_ATAPI;
812        } else if (usb_test_quirk(uaa, UQ_MSC_FORCE_PROTO_UFI)) {
813                proto &= ~UMASS_PROTO_COMMAND;
814                proto |= UMASS_PROTO_UFI;
815        } else if (usb_test_quirk(uaa, UQ_MSC_FORCE_PROTO_RBC)) {
816                proto &= ~UMASS_PROTO_COMMAND;
817                proto |= UMASS_PROTO_RBC;
818        }
819
820        /* Check if the protocol is invalid */
821
822        if ((proto & UMASS_PROTO_COMMAND) == 0) {
823                ret.error = ENXIO;
824                goto done;
825        }
826
827        if ((proto & UMASS_PROTO_WIRE) == 0) {
828                ret.error = ENXIO;
829                goto done;
830        }
831
832        /* Search for quirks */
833
834        if (usb_test_quirk(uaa, UQ_MSC_NO_TEST_UNIT_READY))
835                quirks |= NO_TEST_UNIT_READY;
836        if (usb_test_quirk(uaa, UQ_MSC_NO_RS_CLEAR_UA))
837                quirks |= RS_NO_CLEAR_UA;
838        if (usb_test_quirk(uaa, UQ_MSC_NO_START_STOP))
839                quirks |= NO_START_STOP;
840        if (usb_test_quirk(uaa, UQ_MSC_NO_GETMAXLUN))
841                quirks |= NO_GETMAXLUN;
842        if (usb_test_quirk(uaa, UQ_MSC_NO_INQUIRY))
843                quirks |= NO_INQUIRY;
844        if (usb_test_quirk(uaa, UQ_MSC_NO_INQUIRY_EVPD))
845                quirks |= NO_INQUIRY_EVPD;
846        if (usb_test_quirk(uaa, UQ_MSC_NO_PREVENT_ALLOW))
847                quirks |= NO_PREVENT_ALLOW;
848        if (usb_test_quirk(uaa, UQ_MSC_NO_SYNC_CACHE))
849                quirks |= NO_SYNCHRONIZE_CACHE;
850        if (usb_test_quirk(uaa, UQ_MSC_SHUTTLE_INIT))
851                quirks |= SHUTTLE_INIT;
852        if (usb_test_quirk(uaa, UQ_MSC_ALT_IFACE_1))
853                quirks |= ALT_IFACE_1;
854        if (usb_test_quirk(uaa, UQ_MSC_FLOPPY_SPEED))
855                quirks |= FLOPPY_SPEED;
856        if (usb_test_quirk(uaa, UQ_MSC_IGNORE_RESIDUE))
857                quirks |= IGNORE_RESIDUE;
858        if (usb_test_quirk(uaa, UQ_MSC_WRONG_CSWSIG))
859                quirks |= WRONG_CSWSIG;
860        if (usb_test_quirk(uaa, UQ_MSC_RBC_PAD_TO_12))
861                quirks |= RBC_PAD_TO_12;
862        if (usb_test_quirk(uaa, UQ_MSC_READ_CAP_OFFBY1))
863                quirks |= READ_CAPACITY_OFFBY1;
864        if (usb_test_quirk(uaa, UQ_MSC_FORCE_SHORT_INQ))
865                quirks |= FORCE_SHORT_INQUIRY;
866
867done:
868        ret.quirks = quirks;
869        ret.proto = proto;
870        return (ret);
871}
872
873static int
874umass_probe(device_t dev)
875{
876        struct usb_attach_arg *uaa = device_get_ivars(dev);
877        struct umass_probe_proto temp;
878
879        if (uaa->usb_mode != USB_MODE_HOST) {
880                return (ENXIO);
881        }
882        temp = umass_probe_proto(dev, uaa);
883
884        return (temp.error);
885}
886
887static int
888umass_attach(device_t dev)
889{
890        struct umass_softc *sc = device_get_softc(dev);
891        struct usb_attach_arg *uaa = device_get_ivars(dev);
892        struct umass_probe_proto temp = umass_probe_proto(dev, uaa);
893        struct usb_interface_descriptor *id;
894        int err;
895
896        /*
897         * NOTE: the softc struct is cleared in device_set_driver.
898         * We can safely call umass_detach without specifically
899         * initializing the struct.
900         */
901
902        sc->sc_dev = dev;
903        sc->sc_udev = uaa->device;
904        sc->sc_proto = temp.proto;
905        sc->sc_quirks = temp.quirks;
906        sc->sc_unit = device_get_unit(dev);
907
908        snprintf(sc->sc_name, sizeof(sc->sc_name),
909            "%s", device_get_nameunit(dev));
910
911        device_set_usb_desc(dev);
912
913        mtx_init(&sc->sc_mtx, device_get_nameunit(dev),
914            NULL, MTX_DEF | MTX_RECURSE);
915
916        /* get interface index */
917
918        id = usbd_get_interface_descriptor(uaa->iface);
919        if (id == NULL) {
920                device_printf(dev, "failed to get "
921                    "interface number\n");
922                goto detach;
923        }
924        sc->sc_iface_no = id->bInterfaceNumber;
925
926#ifdef USB_DEBUG
927        device_printf(dev, " ");
928
929        switch (sc->sc_proto & UMASS_PROTO_COMMAND) {
930        case UMASS_PROTO_SCSI:
931                printf("SCSI");
932                break;
933        case UMASS_PROTO_ATAPI:
934                printf("8070i (ATAPI)");
935                break;
936        case UMASS_PROTO_UFI:
937                printf("UFI");
938                break;
939        case UMASS_PROTO_RBC:
940                printf("RBC");
941                break;
942        default:
943                printf("(unknown 0x%02x)",
944                    sc->sc_proto & UMASS_PROTO_COMMAND);
945                break;
946        }
947
948        printf(" over ");
949
950        switch (sc->sc_proto & UMASS_PROTO_WIRE) {
951        case UMASS_PROTO_BBB:
952                printf("Bulk-Only");
953                break;
954        case UMASS_PROTO_CBI:           /* uses Comand/Bulk pipes */
955                printf("CBI");
956                break;
957        case UMASS_PROTO_CBI_I: /* uses Comand/Bulk/Interrupt pipes */
958                printf("CBI with CCI");
959                break;
960        default:
961                printf("(unknown 0x%02x)",
962                    sc->sc_proto & UMASS_PROTO_WIRE);
963        }
964
965        printf("; quirks = 0x%04x\n", sc->sc_quirks);
966#endif
967
968        if (sc->sc_quirks & ALT_IFACE_1) {
969                err = usbd_set_alt_interface_index
970                    (uaa->device, uaa->info.bIfaceIndex, 1);
971
972                if (err) {
973                        DPRINTF(sc, UDMASS_USB, "could not switch to "
974                            "Alt Interface 1\n");
975                        goto detach;
976                }
977        }
978        /* allocate all required USB transfers */
979
980        if (sc->sc_proto & UMASS_PROTO_BBB) {
981
982                err = usbd_transfer_setup(uaa->device,
983                    &uaa->info.bIfaceIndex, sc->sc_xfer, umass_bbb_config,
984                    UMASS_T_BBB_MAX, sc, &sc->sc_mtx);
985
986                /* skip reset first time */
987                sc->sc_last_xfer_index = UMASS_T_BBB_COMMAND;
988
989        } else if (sc->sc_proto & (UMASS_PROTO_CBI | UMASS_PROTO_CBI_I)) {
990
991                err = usbd_transfer_setup(uaa->device,
992                    &uaa->info.bIfaceIndex, sc->sc_xfer, umass_cbi_config,
993                    UMASS_T_CBI_MAX, sc, &sc->sc_mtx);
994
995                /* skip reset first time */
996                sc->sc_last_xfer_index = UMASS_T_CBI_COMMAND;
997
998        } else {
999                err = USB_ERR_INVAL;
1000        }
1001
1002        if (err) {
1003                device_printf(dev, "could not setup required "
1004                    "transfers, %s\n", usbd_errstr(err));
1005                goto detach;
1006        }
1007#ifdef USB_DEBUG
1008        if (umass_throttle > 0) {
1009                uint8_t x;
1010                int iv;
1011
1012                iv = umass_throttle;
1013
1014                if (iv < 1)
1015                        iv = 1;
1016                else if (iv > 8000)
1017                        iv = 8000;
1018
1019                for (x = 0; x != UMASS_T_MAX; x++) {
1020                        if (sc->sc_xfer[x] != NULL)
1021                                usbd_xfer_set_interval(sc->sc_xfer[x], iv);
1022                }
1023        }
1024#endif
1025        sc->sc_transform =
1026            (sc->sc_proto & UMASS_PROTO_SCSI) ? &umass_scsi_transform :
1027            (sc->sc_proto & UMASS_PROTO_UFI) ? &umass_ufi_transform :
1028            (sc->sc_proto & UMASS_PROTO_ATAPI) ? &umass_atapi_transform :
1029            (sc->sc_proto & UMASS_PROTO_RBC) ? &umass_rbc_transform :
1030            &umass_no_transform;
1031
1032        /* from here onwards the device can be used. */
1033
1034        if (sc->sc_quirks & SHUTTLE_INIT) {
1035                umass_init_shuttle(sc);
1036        }
1037        /* get the maximum LUN supported by the device */
1038
1039        if (((sc->sc_proto & UMASS_PROTO_WIRE) == UMASS_PROTO_BBB) &&
1040            !(sc->sc_quirks & NO_GETMAXLUN))
1041                sc->sc_maxlun = umass_bbb_get_max_lun(sc);
1042        else
1043                sc->sc_maxlun = 0;
1044
1045        /* Prepare the SCSI command block */
1046        sc->cam_scsi_sense.opcode = REQUEST_SENSE;
1047        sc->cam_scsi_test_unit_ready.opcode = TEST_UNIT_READY;
1048
1049        /* register the SIM */
1050        err = umass_cam_attach_sim(sc);
1051        if (err) {
1052                goto detach;
1053        }
1054#ifndef __rtems__
1055        /* scan the SIM */
1056        umass_cam_attach(sc);
1057#endif /* __rtems__ */
1058
1059        DPRINTF(sc, UDMASS_GEN, "Attach finished\n");
1060
1061        return (0);                     /* success */
1062
1063detach:
1064        umass_detach(dev);
1065        return (ENXIO);                 /* failure */
1066}
1067
1068static int
1069umass_detach(device_t dev)
1070{
1071        struct umass_softc *sc = device_get_softc(dev);
1072
1073        DPRINTF(sc, UDMASS_USB, "\n");
1074
1075        /* teardown our statemachine */
1076
1077        usbd_transfer_unsetup(sc->sc_xfer, UMASS_T_MAX);
1078
1079        mtx_lock(&sc->sc_mtx);
1080
1081        /* cancel any leftover CCB's */
1082
1083        umass_cancel_ccb(sc);
1084
1085        umass_cam_detach_sim(sc);
1086
1087        mtx_unlock(&sc->sc_mtx);
1088
1089        mtx_destroy(&sc->sc_mtx);
1090
1091        return (0);                     /* success */
1092}
1093
1094static void
1095umass_init_shuttle(struct umass_softc *sc)
1096{
1097        struct usb_device_request req;
1098        usb_error_t err;
1099        uint8_t status[2] = {0, 0};
1100
1101        /*
1102         * The Linux driver does this, but no one can tell us what the
1103         * command does.
1104         */
1105        req.bmRequestType = UT_READ_VENDOR_DEVICE;
1106        req.bRequest = 1;               /* XXX unknown command */
1107        USETW(req.wValue, 0);
1108        req.wIndex[0] = sc->sc_iface_no;
1109        req.wIndex[1] = 0;
1110        USETW(req.wLength, sizeof(status));
1111        err = usbd_do_request(sc->sc_udev, NULL, &req, &status);
1112
1113        DPRINTF(sc, UDMASS_GEN, "Shuttle init returned 0x%02x%02x\n",
1114            status[0], status[1]);
1115}
1116
1117/*
1118 * Generic functions to handle transfers
1119 */
1120
1121static void
1122umass_transfer_start(struct umass_softc *sc, uint8_t xfer_index)
1123{
1124        DPRINTF(sc, UDMASS_GEN, "transfer index = "
1125            "%d\n", xfer_index);
1126
1127        if (sc->sc_xfer[xfer_index]) {
1128                sc->sc_last_xfer_index = xfer_index;
1129                usbd_transfer_start(sc->sc_xfer[xfer_index]);
1130        } else {
1131                umass_cancel_ccb(sc);
1132        }
1133}
1134
1135static void
1136umass_reset(struct umass_softc *sc)
1137{
1138        DPRINTF(sc, UDMASS_GEN, "resetting device\n");
1139
1140        /*
1141         * stop the last transfer, if not already stopped:
1142         */
1143        usbd_transfer_stop(sc->sc_xfer[sc->sc_last_xfer_index]);
1144        umass_transfer_start(sc, 0);
1145}
1146
1147static void
1148umass_cancel_ccb(struct umass_softc *sc)
1149{
1150        union ccb *ccb;
1151
1152        mtx_assert(&sc->sc_mtx, MA_OWNED);
1153
1154        ccb = sc->sc_transfer.ccb;
1155        sc->sc_transfer.ccb = NULL;
1156        sc->sc_last_xfer_index = 0;
1157
1158        if (ccb) {
1159                (sc->sc_transfer.callback)
1160                    (sc, ccb, (sc->sc_transfer.data_len -
1161                    sc->sc_transfer.actlen), STATUS_WIRE_FAILED);
1162        }
1163}
1164
1165static void
1166umass_tr_error(struct usb_xfer *xfer, usb_error_t error)
1167{
1168        struct umass_softc *sc = usbd_xfer_softc(xfer);
1169
1170        if (error != USB_ERR_CANCELLED) {
1171
1172                DPRINTF(sc, UDMASS_GEN, "transfer error, %s -> "
1173                    "reset\n", usbd_errstr(error));
1174        }
1175        umass_cancel_ccb(sc);
1176}
1177
1178/*
1179 * BBB protocol specific functions
1180 */
1181
1182static void
1183umass_t_bbb_reset1_callback(struct usb_xfer *xfer, usb_error_t error)
1184{
1185        struct umass_softc *sc = usbd_xfer_softc(xfer);
1186        struct usb_device_request req;
1187        struct usb_page_cache *pc;
1188
1189        switch (USB_GET_STATE(xfer)) {
1190        case USB_ST_TRANSFERRED:
1191                umass_transfer_start(sc, UMASS_T_BBB_RESET2);
1192                return;
1193
1194        case USB_ST_SETUP:
1195                /*
1196                 * Reset recovery (5.3.4 in Universal Serial Bus Mass Storage Class)
1197                 *
1198                 * For Reset Recovery the host shall issue in the following order:
1199                 * a) a Bulk-Only Mass Storage Reset
1200                 * b) a Clear Feature HALT to the Bulk-In endpoint
1201                 * c) a Clear Feature HALT to the Bulk-Out endpoint
1202                 *
1203                 * This is done in 3 steps, using 3 transfers:
1204                 * UMASS_T_BBB_RESET1
1205                 * UMASS_T_BBB_RESET2
1206                 * UMASS_T_BBB_RESET3
1207                 */
1208
1209                DPRINTF(sc, UDMASS_BBB, "BBB reset!\n");
1210
1211                req.bmRequestType = UT_WRITE_CLASS_INTERFACE;
1212                req.bRequest = UR_BBB_RESET;    /* bulk only reset */
1213                USETW(req.wValue, 0);
1214                req.wIndex[0] = sc->sc_iface_no;
1215                req.wIndex[1] = 0;
1216                USETW(req.wLength, 0);
1217
1218                pc = usbd_xfer_get_frame(xfer, 0);
1219                usbd_copy_in(pc, 0, &req, sizeof(req));
1220
1221                usbd_xfer_set_frame_len(xfer, 0, sizeof(req));
1222                usbd_xfer_set_frames(xfer, 1);
1223                usbd_transfer_submit(xfer);
1224                return;
1225
1226        default:                        /* Error */
1227                umass_tr_error(xfer, error);
1228                return;
1229        }
1230}
1231
1232static void
1233umass_t_bbb_reset2_callback(struct usb_xfer *xfer, usb_error_t error)
1234{
1235        umass_t_bbb_data_clear_stall_callback(xfer, UMASS_T_BBB_RESET3,
1236            UMASS_T_BBB_DATA_READ, error);
1237}
1238
1239static void
1240umass_t_bbb_reset3_callback(struct usb_xfer *xfer, usb_error_t error)
1241{
1242        umass_t_bbb_data_clear_stall_callback(xfer, UMASS_T_BBB_COMMAND,
1243            UMASS_T_BBB_DATA_WRITE, error);
1244}
1245
1246static void
1247umass_t_bbb_data_clear_stall_callback(struct usb_xfer *xfer,
1248    uint8_t next_xfer, uint8_t stall_xfer, usb_error_t error)
1249{
1250        struct umass_softc *sc = usbd_xfer_softc(xfer);
1251
1252        switch (USB_GET_STATE(xfer)) {
1253        case USB_ST_TRANSFERRED:
1254tr_transferred:
1255                umass_transfer_start(sc, next_xfer);
1256                return;
1257
1258        case USB_ST_SETUP:
1259                if (usbd_clear_stall_callback(xfer, sc->sc_xfer[stall_xfer])) {
1260                        goto tr_transferred;
1261                }
1262                return;
1263
1264        default:                        /* Error */
1265                umass_tr_error(xfer, error);
1266                return;
1267        }
1268}
1269
1270static void
1271umass_t_bbb_command_callback(struct usb_xfer *xfer, usb_error_t error)
1272{
1273        struct umass_softc *sc = usbd_xfer_softc(xfer);
1274        union ccb *ccb = sc->sc_transfer.ccb;
1275        struct usb_page_cache *pc;
1276        uint32_t tag;
1277
1278        switch (USB_GET_STATE(xfer)) {
1279        case USB_ST_TRANSFERRED:
1280                umass_transfer_start
1281                    (sc, ((sc->sc_transfer.dir == DIR_IN) ? UMASS_T_BBB_DATA_READ :
1282                    (sc->sc_transfer.dir == DIR_OUT) ? UMASS_T_BBB_DATA_WRITE :
1283                    UMASS_T_BBB_STATUS));
1284                return;
1285
1286        case USB_ST_SETUP:
1287
1288                sc->sc_status_try = 0;
1289
1290                if (ccb) {
1291
1292                        /*
1293                         * the initial value is not important,
1294                         * as long as the values are unique:
1295                         */
1296                        tag = UGETDW(sc->cbw.dCBWTag) + 1;
1297
1298                        USETDW(sc->cbw.dCBWSignature, CBWSIGNATURE);
1299                        USETDW(sc->cbw.dCBWTag, tag);
1300
1301                        /*
1302                         * dCBWDataTransferLength:
1303                         *   This field indicates the number of bytes of data that the host
1304                         *   intends to transfer on the IN or OUT Bulk endpoint(as indicated by
1305                         *   the Direction bit) during the execution of this command. If this
1306                         *   field is set to 0, the device will expect that no data will be
1307                         *   transferred IN or OUT during this command, regardless of the value
1308                         *   of the Direction bit defined in dCBWFlags.
1309                         */
1310                        USETDW(sc->cbw.dCBWDataTransferLength, sc->sc_transfer.data_len);
1311
1312                        /*
1313                         * dCBWFlags:
1314                         *   The bits of the Flags field are defined as follows:
1315                         *     Bits 0-6  reserved
1316                         *     Bit  7    Direction - this bit shall be ignored if the
1317                         *                           dCBWDataTransferLength field is zero.
1318                         *               0 = data Out from host to device
1319                         *               1 = data In from device to host
1320                         */
1321                        sc->cbw.bCBWFlags = ((sc->sc_transfer.dir == DIR_IN) ?
1322                            CBWFLAGS_IN : CBWFLAGS_OUT);
1323                        sc->cbw.bCBWLUN = sc->sc_transfer.lun;
1324
1325                        if (sc->sc_transfer.cmd_len > sizeof(sc->cbw.CBWCDB)) {
1326                                sc->sc_transfer.cmd_len = sizeof(sc->cbw.CBWCDB);
1327                                DPRINTF(sc, UDMASS_BBB, "Truncating long command!\n");
1328                        }
1329                        sc->cbw.bCDBLength = sc->sc_transfer.cmd_len;
1330
1331                        /* copy SCSI command data */
1332                        memcpy(sc->cbw.CBWCDB, sc->sc_transfer.cmd_data,
1333                            sc->sc_transfer.cmd_len);
1334
1335                        /* clear remaining command area */
1336                        memset(sc->cbw.CBWCDB +
1337                            sc->sc_transfer.cmd_len, 0,
1338                            sizeof(sc->cbw.CBWCDB) -
1339                            sc->sc_transfer.cmd_len);
1340
1341                        DIF(UDMASS_BBB, umass_bbb_dump_cbw(sc, &sc->cbw));
1342
1343                        pc = usbd_xfer_get_frame(xfer, 0);
1344                        usbd_copy_in(pc, 0, &sc->cbw, sizeof(sc->cbw));
1345                        usbd_xfer_set_frame_len(xfer, 0, sizeof(sc->cbw));
1346
1347                        usbd_transfer_submit(xfer);
1348                }
1349                return;
1350
1351        default:                        /* Error */
1352                umass_tr_error(xfer, error);
1353                return;
1354        }
1355}
1356
1357static void
1358umass_t_bbb_data_read_callback(struct usb_xfer *xfer, usb_error_t error)
1359{
1360        struct umass_softc *sc = usbd_xfer_softc(xfer);
1361        uint32_t max_bulk = usbd_xfer_max_len(xfer);
1362        int actlen, sumlen;
1363
1364        usbd_xfer_status(xfer, &actlen, &sumlen, NULL, NULL);
1365
1366        switch (USB_GET_STATE(xfer)) {
1367        case USB_ST_TRANSFERRED:
1368                sc->sc_transfer.data_rem -= actlen;
1369                sc->sc_transfer.data_ptr += actlen;
1370                sc->sc_transfer.actlen += actlen;
1371
1372                if (actlen < sumlen) {
1373                        /* short transfer */
1374                        sc->sc_transfer.data_rem = 0;
1375                }
1376        case USB_ST_SETUP:
1377                DPRINTF(sc, UDMASS_BBB, "max_bulk=%d, data_rem=%d\n",
1378                    max_bulk, sc->sc_transfer.data_rem);
1379
1380                if (sc->sc_transfer.data_rem == 0) {
1381                        umass_transfer_start(sc, UMASS_T_BBB_STATUS);
1382                        return;
1383                }
1384                if (max_bulk > sc->sc_transfer.data_rem) {
1385                        max_bulk = sc->sc_transfer.data_rem;
1386                }
1387                usbd_xfer_set_timeout(xfer, sc->sc_transfer.data_timeout);
1388
1389                usbd_xfer_set_frame_data(xfer, 0, sc->sc_transfer.data_ptr,
1390                    max_bulk);
1391
1392                usbd_transfer_submit(xfer);
1393                return;
1394
1395        default:                        /* Error */
1396                if (error == USB_ERR_CANCELLED) {
1397                        umass_tr_error(xfer, error);
1398                } else {
1399                        umass_transfer_start(sc, UMASS_T_BBB_DATA_RD_CS);
1400                }
1401                return;
1402        }
1403}
1404
1405static void
1406umass_t_bbb_data_rd_cs_callback(struct usb_xfer *xfer, usb_error_t error)
1407{
1408        umass_t_bbb_data_clear_stall_callback(xfer, UMASS_T_BBB_STATUS,
1409            UMASS_T_BBB_DATA_READ, error);
1410}
1411
1412static void
1413umass_t_bbb_data_write_callback(struct usb_xfer *xfer, usb_error_t error)
1414{
1415        struct umass_softc *sc = usbd_xfer_softc(xfer);
1416        uint32_t max_bulk = usbd_xfer_max_len(xfer);
1417        int actlen, sumlen;
1418
1419        usbd_xfer_status(xfer, &actlen, &sumlen, NULL, NULL);
1420
1421        switch (USB_GET_STATE(xfer)) {
1422        case USB_ST_TRANSFERRED:
1423                sc->sc_transfer.data_rem -= actlen;
1424                sc->sc_transfer.data_ptr += actlen;
1425                sc->sc_transfer.actlen += actlen;
1426
1427                if (actlen < sumlen) {
1428                        /* short transfer */
1429                        sc->sc_transfer.data_rem = 0;
1430                }
1431        case USB_ST_SETUP:
1432                DPRINTF(sc, UDMASS_BBB, "max_bulk=%d, data_rem=%d\n",
1433                    max_bulk, sc->sc_transfer.data_rem);
1434
1435                if (sc->sc_transfer.data_rem == 0) {
1436                        umass_transfer_start(sc, UMASS_T_BBB_STATUS);
1437                        return;
1438                }
1439                if (max_bulk > sc->sc_transfer.data_rem) {
1440                        max_bulk = sc->sc_transfer.data_rem;
1441                }
1442                usbd_xfer_set_timeout(xfer, sc->sc_transfer.data_timeout);
1443
1444                usbd_xfer_set_frame_data(xfer, 0, sc->sc_transfer.data_ptr,
1445                    max_bulk);
1446
1447                usbd_transfer_submit(xfer);
1448                return;
1449
1450        default:                        /* Error */
1451                if (error == USB_ERR_CANCELLED) {
1452                        umass_tr_error(xfer, error);
1453                } else {
1454                        umass_transfer_start(sc, UMASS_T_BBB_DATA_WR_CS);
1455                }
1456                return;
1457        }
1458}
1459
1460static void
1461umass_t_bbb_data_wr_cs_callback(struct usb_xfer *xfer, usb_error_t error)
1462{
1463        umass_t_bbb_data_clear_stall_callback(xfer, UMASS_T_BBB_STATUS,
1464            UMASS_T_BBB_DATA_WRITE, error);
1465}
1466
1467static void
1468umass_t_bbb_status_callback(struct usb_xfer *xfer, usb_error_t error)
1469{
1470        struct umass_softc *sc = usbd_xfer_softc(xfer);
1471        union ccb *ccb = sc->sc_transfer.ccb;
1472        struct usb_page_cache *pc;
1473        uint32_t residue;
1474        int actlen;
1475
1476        usbd_xfer_status(xfer, &actlen, NULL, NULL, NULL);
1477
1478        switch (USB_GET_STATE(xfer)) {
1479        case USB_ST_TRANSFERRED:
1480
1481                /*
1482                 * Do a full reset if there is something wrong with the CSW:
1483                 */
1484                sc->sc_status_try = 1;
1485
1486                /* Zero missing parts of the CSW: */
1487
1488                if (actlen < (int)sizeof(sc->csw))
1489                        memset(&sc->csw, 0, sizeof(sc->csw));
1490
1491                pc = usbd_xfer_get_frame(xfer, 0);
1492                usbd_copy_out(pc, 0, &sc->csw, actlen);
1493
1494                DIF(UDMASS_BBB, umass_bbb_dump_csw(sc, &sc->csw));
1495
1496                residue = UGETDW(sc->csw.dCSWDataResidue);
1497
1498                if ((!residue) || (sc->sc_quirks & IGNORE_RESIDUE)) {
1499                        residue = (sc->sc_transfer.data_len -
1500                            sc->sc_transfer.actlen);
1501                }
1502                if (residue > sc->sc_transfer.data_len) {
1503                        DPRINTF(sc, UDMASS_BBB, "truncating residue from %d "
1504                            "to %d bytes\n", residue, sc->sc_transfer.data_len);
1505                        residue = sc->sc_transfer.data_len;
1506                }
1507                /* translate weird command-status signatures: */
1508                if (sc->sc_quirks & WRONG_CSWSIG) {
1509
1510                        uint32_t temp = UGETDW(sc->csw.dCSWSignature);
1511
1512                        if ((temp == CSWSIGNATURE_OLYMPUS_C1) ||
1513                            (temp == CSWSIGNATURE_IMAGINATION_DBX1)) {
1514                                USETDW(sc->csw.dCSWSignature, CSWSIGNATURE);
1515                        }
1516                }
1517                /* check CSW and handle eventual error */
1518                if (UGETDW(sc->csw.dCSWSignature) != CSWSIGNATURE) {
1519                        DPRINTF(sc, UDMASS_BBB, "bad CSW signature 0x%08x != 0x%08x\n",
1520                            UGETDW(sc->csw.dCSWSignature), CSWSIGNATURE);
1521                        /*
1522                         * Invalid CSW: Wrong signature or wrong tag might
1523                         * indicate that we lost synchronization. Reset the
1524                         * device.
1525                         */
1526                        goto tr_error;
1527                } else if (UGETDW(sc->csw.dCSWTag) != UGETDW(sc->cbw.dCBWTag)) {
1528                        DPRINTF(sc, UDMASS_BBB, "Invalid CSW: tag 0x%08x should be "
1529                            "0x%08x\n", UGETDW(sc->csw.dCSWTag),
1530                            UGETDW(sc->cbw.dCBWTag));
1531                        goto tr_error;
1532                } else if (sc->csw.bCSWStatus > CSWSTATUS_PHASE) {
1533                        DPRINTF(sc, UDMASS_BBB, "Invalid CSW: status %d > %d\n",
1534                            sc->csw.bCSWStatus, CSWSTATUS_PHASE);
1535                        goto tr_error;
1536                } else if (sc->csw.bCSWStatus == CSWSTATUS_PHASE) {
1537                        DPRINTF(sc, UDMASS_BBB, "Phase error, residue = "
1538                            "%d\n", residue);
1539                        goto tr_error;
1540                } else if (sc->sc_transfer.actlen > sc->sc_transfer.data_len) {
1541                        DPRINTF(sc, UDMASS_BBB, "Buffer overrun %d > %d\n",
1542                            sc->sc_transfer.actlen, sc->sc_transfer.data_len);
1543                        goto tr_error;
1544                } else if (sc->csw.bCSWStatus == CSWSTATUS_FAILED) {
1545                        DPRINTF(sc, UDMASS_BBB, "Command failed, residue = "
1546                            "%d\n", residue);
1547
1548                        sc->sc_transfer.ccb = NULL;
1549
1550                        sc->sc_last_xfer_index = UMASS_T_BBB_COMMAND;
1551
1552                        (sc->sc_transfer.callback)
1553                            (sc, ccb, residue, STATUS_CMD_FAILED);
1554                } else {
1555                        sc->sc_transfer.ccb = NULL;
1556
1557                        sc->sc_last_xfer_index = UMASS_T_BBB_COMMAND;
1558
1559                        (sc->sc_transfer.callback)
1560                            (sc, ccb, residue, STATUS_CMD_OK);
1561                }
1562                return;
1563
1564        case USB_ST_SETUP:
1565                usbd_xfer_set_frame_len(xfer, 0, usbd_xfer_max_len(xfer));
1566                usbd_transfer_submit(xfer);
1567                return;
1568
1569        default:
1570tr_error:
1571                DPRINTF(sc, UDMASS_BBB, "Failed to read CSW: %s, try %d\n",
1572                    usbd_errstr(error), sc->sc_status_try);
1573
1574                if ((error == USB_ERR_CANCELLED) ||
1575                    (sc->sc_status_try)) {
1576                        umass_tr_error(xfer, error);
1577                } else {
1578                        sc->sc_status_try = 1;
1579                        umass_transfer_start(sc, UMASS_T_BBB_DATA_RD_CS);
1580                }
1581                return;
1582        }
1583}
1584
1585static void
1586umass_command_start(struct umass_softc *sc, uint8_t dir,
1587    void *data_ptr, uint32_t data_len,
1588    uint32_t data_timeout, umass_callback_t *callback,
1589    union ccb *ccb)
1590{
1591        sc->sc_transfer.lun = ccb->ccb_h.target_lun;
1592
1593        /*
1594         * NOTE: assumes that "sc->sc_transfer.cmd_data" and
1595         * "sc->sc_transfer.cmd_len" has been properly
1596         * initialized.
1597         */
1598
1599        sc->sc_transfer.dir = data_len ? dir : DIR_NONE;
1600        sc->sc_transfer.data_ptr = data_ptr;
1601        sc->sc_transfer.data_len = data_len;
1602        sc->sc_transfer.data_rem = data_len;
1603        sc->sc_transfer.data_timeout = (data_timeout + UMASS_TIMEOUT);
1604
1605        sc->sc_transfer.actlen = 0;
1606        sc->sc_transfer.callback = callback;
1607        sc->sc_transfer.ccb = ccb;
1608
1609        if (sc->sc_xfer[sc->sc_last_xfer_index]) {
1610                usbd_transfer_start(sc->sc_xfer[sc->sc_last_xfer_index]);
1611        } else {
1612                umass_cancel_ccb(sc);
1613        }
1614}
1615
1616static uint8_t
1617umass_bbb_get_max_lun(struct umass_softc *sc)
1618{
1619        struct usb_device_request req;
1620        usb_error_t err;
1621        uint8_t buf = 0;
1622
1623        /* The Get Max Lun command is a class-specific request. */
1624        req.bmRequestType = UT_READ_CLASS_INTERFACE;
1625        req.bRequest = UR_BBB_GET_MAX_LUN;
1626        USETW(req.wValue, 0);
1627        req.wIndex[0] = sc->sc_iface_no;
1628        req.wIndex[1] = 0;
1629        USETW(req.wLength, 1);
1630
1631        err = usbd_do_request(sc->sc_udev, NULL, &req, &buf);
1632        if (err) {
1633                buf = 0;
1634
1635                /* Device doesn't support Get Max Lun request. */
1636                printf("%s: Get Max Lun not supported (%s)\n",
1637                    sc->sc_name, usbd_errstr(err));
1638        }
1639        return (buf);
1640}
1641
1642/*
1643 * Command/Bulk/Interrupt (CBI) specific functions
1644 */
1645
1646static void
1647umass_cbi_start_status(struct umass_softc *sc)
1648{
1649        if (sc->sc_xfer[UMASS_T_CBI_STATUS]) {
1650                umass_transfer_start(sc, UMASS_T_CBI_STATUS);
1651        } else {
1652                union ccb *ccb = sc->sc_transfer.ccb;
1653
1654                sc->sc_transfer.ccb = NULL;
1655
1656                sc->sc_last_xfer_index = UMASS_T_CBI_COMMAND;
1657
1658                (sc->sc_transfer.callback)
1659                    (sc, ccb, (sc->sc_transfer.data_len -
1660                    sc->sc_transfer.actlen), STATUS_CMD_UNKNOWN);
1661        }
1662}
1663
1664static void
1665umass_t_cbi_reset1_callback(struct usb_xfer *xfer, usb_error_t error)
1666{
1667        struct umass_softc *sc = usbd_xfer_softc(xfer);
1668        struct usb_device_request req;
1669        struct usb_page_cache *pc;
1670        uint8_t buf[UMASS_CBI_DIAGNOSTIC_CMDLEN];
1671
1672        uint8_t i;
1673
1674        switch (USB_GET_STATE(xfer)) {
1675        case USB_ST_TRANSFERRED:
1676                umass_transfer_start(sc, UMASS_T_CBI_RESET2);
1677                break;
1678
1679        case USB_ST_SETUP:
1680                /*
1681                 * Command Block Reset Protocol
1682                 *
1683                 * First send a reset request to the device. Then clear
1684                 * any possibly stalled bulk endpoints.
1685                 *
1686                 * This is done in 3 steps, using 3 transfers:
1687                 * UMASS_T_CBI_RESET1
1688                 * UMASS_T_CBI_RESET2
1689                 * UMASS_T_CBI_RESET3
1690                 * UMASS_T_CBI_RESET4 (only if there is an interrupt endpoint)
1691                 */
1692
1693                DPRINTF(sc, UDMASS_CBI, "CBI reset!\n");
1694
1695                req.bmRequestType = UT_WRITE_CLASS_INTERFACE;
1696                req.bRequest = UR_CBI_ADSC;
1697                USETW(req.wValue, 0);
1698                req.wIndex[0] = sc->sc_iface_no;
1699                req.wIndex[1] = 0;
1700                USETW(req.wLength, UMASS_CBI_DIAGNOSTIC_CMDLEN);
1701
1702                /*
1703                 * The 0x1d code is the SEND DIAGNOSTIC command. To
1704                 * distinguish between the two, the last 10 bytes of the CBL
1705                 * is filled with 0xff (section 2.2 of the CBI
1706                 * specification)
1707                 */
1708                buf[0] = 0x1d;          /* Command Block Reset */
1709                buf[1] = 0x04;
1710
1711                for (i = 2; i < UMASS_CBI_DIAGNOSTIC_CMDLEN; i++) {
1712                        buf[i] = 0xff;
1713                }
1714
1715                pc = usbd_xfer_get_frame(xfer, 0);
1716                usbd_copy_in(pc, 0, &req, sizeof(req));
1717                pc = usbd_xfer_get_frame(xfer, 1);
1718                usbd_copy_in(pc, 0, buf, sizeof(buf));
1719
1720                usbd_xfer_set_frame_len(xfer, 0, sizeof(req));
1721                usbd_xfer_set_frame_len(xfer, 1, sizeof(buf));
1722                usbd_xfer_set_frames(xfer, 2);
1723                usbd_transfer_submit(xfer);
1724                break;
1725
1726        default:                        /* Error */
1727                if (error == USB_ERR_CANCELLED)
1728                        umass_tr_error(xfer, error);
1729                else
1730                        umass_transfer_start(sc, UMASS_T_CBI_RESET2);
1731                break;
1732        }
1733}
1734
1735static void
1736umass_t_cbi_reset2_callback(struct usb_xfer *xfer, usb_error_t error)
1737{
1738        umass_t_cbi_data_clear_stall_callback(xfer, UMASS_T_CBI_RESET3,
1739            UMASS_T_CBI_DATA_READ, error);
1740}
1741
1742static void
1743umass_t_cbi_reset3_callback(struct usb_xfer *xfer, usb_error_t error)
1744{
1745        struct umass_softc *sc = usbd_xfer_softc(xfer);
1746
1747        umass_t_cbi_data_clear_stall_callback
1748            (xfer, (sc->sc_xfer[UMASS_T_CBI_RESET4] &&
1749            sc->sc_xfer[UMASS_T_CBI_STATUS]) ?
1750            UMASS_T_CBI_RESET4 : UMASS_T_CBI_COMMAND,
1751            UMASS_T_CBI_DATA_WRITE, error);
1752}
1753
1754static void
1755umass_t_cbi_reset4_callback(struct usb_xfer *xfer, usb_error_t error)
1756{
1757        umass_t_cbi_data_clear_stall_callback(xfer, UMASS_T_CBI_COMMAND,
1758            UMASS_T_CBI_STATUS, error);
1759}
1760
1761static void
1762umass_t_cbi_data_clear_stall_callback(struct usb_xfer *xfer,
1763    uint8_t next_xfer, uint8_t stall_xfer, usb_error_t error)
1764{
1765        struct umass_softc *sc = usbd_xfer_softc(xfer);
1766
1767        switch (USB_GET_STATE(xfer)) {
1768        case USB_ST_TRANSFERRED:
1769tr_transferred:
1770                if (next_xfer == UMASS_T_CBI_STATUS) {
1771                        umass_cbi_start_status(sc);
1772                } else {
1773                        umass_transfer_start(sc, next_xfer);
1774                }
1775                break;
1776
1777        case USB_ST_SETUP:
1778                if (usbd_clear_stall_callback(xfer, sc->sc_xfer[stall_xfer])) {
1779                        goto tr_transferred;    /* should not happen */
1780                }
1781                break;
1782
1783        default:                        /* Error */
1784                umass_tr_error(xfer, error);
1785                break;
1786        }
1787}
1788
1789static void
1790umass_t_cbi_command_callback(struct usb_xfer *xfer, usb_error_t error)
1791{
1792        struct umass_softc *sc = usbd_xfer_softc(xfer);
1793        union ccb *ccb = sc->sc_transfer.ccb;
1794        struct usb_device_request req;
1795        struct usb_page_cache *pc;
1796
1797        switch (USB_GET_STATE(xfer)) {
1798        case USB_ST_TRANSFERRED:
1799
1800                if (sc->sc_transfer.dir == DIR_NONE) {
1801                        umass_cbi_start_status(sc);
1802                } else {
1803                        umass_transfer_start
1804                            (sc, (sc->sc_transfer.dir == DIR_IN) ?
1805                            UMASS_T_CBI_DATA_READ : UMASS_T_CBI_DATA_WRITE);
1806                }
1807                break;
1808
1809        case USB_ST_SETUP:
1810
1811                if (ccb) {
1812
1813                        /*
1814                         * do a CBI transfer with cmd_len bytes from
1815                         * cmd_data, possibly a data phase of data_len
1816                         * bytes from/to the device and finally a status
1817                         * read phase.
1818                         */
1819
1820                        req.bmRequestType = UT_WRITE_CLASS_INTERFACE;
1821                        req.bRequest = UR_CBI_ADSC;
1822                        USETW(req.wValue, 0);
1823                        req.wIndex[0] = sc->sc_iface_no;
1824                        req.wIndex[1] = 0;
1825                        req.wLength[0] = sc->sc_transfer.cmd_len;
1826                        req.wLength[1] = 0;
1827
1828                        pc = usbd_xfer_get_frame(xfer, 0);
1829                        usbd_copy_in(pc, 0, &req, sizeof(req));
1830                        pc = usbd_xfer_get_frame(xfer, 1);
1831                        usbd_copy_in(pc, 0, sc->sc_transfer.cmd_data,
1832                            sc->sc_transfer.cmd_len);
1833
1834                        usbd_xfer_set_frame_len(xfer, 0, sizeof(req));
1835                        usbd_xfer_set_frame_len(xfer, 1, sc->sc_transfer.cmd_len);
1836                        usbd_xfer_set_frames(xfer,
1837                            sc->sc_transfer.cmd_len ? 2 : 1);
1838
1839                        DIF(UDMASS_CBI,
1840                            umass_cbi_dump_cmd(sc,
1841                            sc->sc_transfer.cmd_data,
1842                            sc->sc_transfer.cmd_len));
1843
1844                        usbd_transfer_submit(xfer);
1845                }
1846                break;
1847
1848        default:                        /* Error */
1849                /*
1850                 * STALL on the control pipe can be result of the command error.
1851                 * Attempt to clear this STALL same as for bulk pipe also
1852                 * results in command completion interrupt, but ASC/ASCQ there
1853                 * look like not always valid, so don't bother about it.
1854                 */
1855                if ((error == USB_ERR_STALLED) ||
1856                    (sc->sc_transfer.callback == &umass_cam_cb)) {
1857                        sc->sc_transfer.ccb = NULL;
1858                        (sc->sc_transfer.callback)
1859                            (sc, ccb, sc->sc_transfer.data_len,
1860                            STATUS_CMD_UNKNOWN);
1861                } else {
1862                        umass_tr_error(xfer, error);
1863                        /* skip reset */
1864                        sc->sc_last_xfer_index = UMASS_T_CBI_COMMAND;
1865                }
1866                break;
1867        }
1868}
1869
1870static void
1871umass_t_cbi_data_read_callback(struct usb_xfer *xfer, usb_error_t error)
1872{
1873        struct umass_softc *sc = usbd_xfer_softc(xfer);
1874        uint32_t max_bulk = usbd_xfer_max_len(xfer);
1875        int actlen, sumlen;
1876
1877        usbd_xfer_status(xfer, &actlen, &sumlen, NULL, NULL);
1878
1879        switch (USB_GET_STATE(xfer)) {
1880        case USB_ST_TRANSFERRED:
1881                sc->sc_transfer.data_rem -= actlen;
1882                sc->sc_transfer.data_ptr += actlen;
1883                sc->sc_transfer.actlen += actlen;
1884
1885                if (actlen < sumlen) {
1886                        /* short transfer */
1887                        sc->sc_transfer.data_rem = 0;
1888                }
1889        case USB_ST_SETUP:
1890                DPRINTF(sc, UDMASS_CBI, "max_bulk=%d, data_rem=%d\n",
1891                    max_bulk, sc->sc_transfer.data_rem);
1892
1893                if (sc->sc_transfer.data_rem == 0) {
1894                        umass_cbi_start_status(sc);
1895                        break;
1896                }
1897                if (max_bulk > sc->sc_transfer.data_rem) {
1898                        max_bulk = sc->sc_transfer.data_rem;
1899                }
1900                usbd_xfer_set_timeout(xfer, sc->sc_transfer.data_timeout);
1901
1902                usbd_xfer_set_frame_data(xfer, 0, sc->sc_transfer.data_ptr,
1903                    max_bulk);
1904
1905                usbd_transfer_submit(xfer);
1906                break;
1907
1908        default:                        /* Error */
1909                if ((error == USB_ERR_CANCELLED) ||
1910                    (sc->sc_transfer.callback != &umass_cam_cb)) {
1911                        umass_tr_error(xfer, error);
1912                } else {
1913                        umass_transfer_start(sc, UMASS_T_CBI_DATA_RD_CS);
1914                }
1915                break;
1916        }
1917}
1918
1919static void
1920umass_t_cbi_data_rd_cs_callback(struct usb_xfer *xfer, usb_error_t error)
1921{
1922        umass_t_cbi_data_clear_stall_callback(xfer, UMASS_T_CBI_STATUS,
1923            UMASS_T_CBI_DATA_READ, error);
1924}
1925
1926static void
1927umass_t_cbi_data_write_callback(struct usb_xfer *xfer, usb_error_t error)
1928{
1929        struct umass_softc *sc = usbd_xfer_softc(xfer);
1930        uint32_t max_bulk = usbd_xfer_max_len(xfer);
1931        int actlen, sumlen;
1932
1933        usbd_xfer_status(xfer, &actlen, &sumlen, NULL, NULL);
1934
1935        switch (USB_GET_STATE(xfer)) {
1936        case USB_ST_TRANSFERRED:
1937                sc->sc_transfer.data_rem -= actlen;
1938                sc->sc_transfer.data_ptr += actlen;
1939                sc->sc_transfer.actlen += actlen;
1940
1941                if (actlen < sumlen) {
1942                        /* short transfer */
1943                        sc->sc_transfer.data_rem = 0;
1944                }
1945        case USB_ST_SETUP:
1946                DPRINTF(sc, UDMASS_CBI, "max_bulk=%d, data_rem=%d\n",
1947                    max_bulk, sc->sc_transfer.data_rem);
1948
1949                if (sc->sc_transfer.data_rem == 0) {
1950                        umass_cbi_start_status(sc);
1951                        break;
1952                }
1953                if (max_bulk > sc->sc_transfer.data_rem) {
1954                        max_bulk = sc->sc_transfer.data_rem;
1955                }
1956                usbd_xfer_set_timeout(xfer, sc->sc_transfer.data_timeout);
1957
1958                usbd_xfer_set_frame_data(xfer, 0, sc->sc_transfer.data_ptr,
1959                    max_bulk);
1960
1961                usbd_transfer_submit(xfer);
1962                break;
1963
1964        default:                        /* Error */
1965                if ((error == USB_ERR_CANCELLED) ||
1966                    (sc->sc_transfer.callback != &umass_cam_cb)) {
1967                        umass_tr_error(xfer, error);
1968                } else {
1969                        umass_transfer_start(sc, UMASS_T_CBI_DATA_WR_CS);
1970                }
1971                break;
1972        }
1973}
1974
1975static void
1976umass_t_cbi_data_wr_cs_callback(struct usb_xfer *xfer, usb_error_t error)
1977{
1978        umass_t_cbi_data_clear_stall_callback(xfer, UMASS_T_CBI_STATUS,
1979            UMASS_T_CBI_DATA_WRITE, error);
1980}
1981
1982static void
1983umass_t_cbi_status_callback(struct usb_xfer *xfer, usb_error_t error)
1984{
1985        struct umass_softc *sc = usbd_xfer_softc(xfer);
1986        union ccb *ccb = sc->sc_transfer.ccb;
1987        struct usb_page_cache *pc;
1988        uint32_t residue;
1989        uint8_t status;
1990        int actlen;
1991
1992        usbd_xfer_status(xfer, &actlen, NULL, NULL, NULL);
1993
1994        switch (USB_GET_STATE(xfer)) {
1995        case USB_ST_TRANSFERRED:
1996
1997                if (actlen < (int)sizeof(sc->sbl)) {
1998                        goto tr_setup;
1999                }
2000                pc = usbd_xfer_get_frame(xfer, 0);
2001                usbd_copy_out(pc, 0, &sc->sbl, sizeof(sc->sbl));
2002
2003                residue = (sc->sc_transfer.data_len -
2004                    sc->sc_transfer.actlen);
2005
2006                /* dissect the information in the buffer */
2007
2008                if (sc->sc_proto & UMASS_PROTO_UFI) {
2009
2010                        /*
2011                         * Section 3.4.3.1.3 specifies that the UFI command
2012                         * protocol returns an ASC and ASCQ in the interrupt
2013                         * data block.
2014                         */
2015
2016                        DPRINTF(sc, UDMASS_CBI, "UFI CCI, ASC = 0x%02x, "
2017                            "ASCQ = 0x%02x\n", sc->sbl.ufi.asc,
2018                            sc->sbl.ufi.ascq);
2019
2020                        status = (((sc->sbl.ufi.asc == 0) &&
2021                            (sc->sbl.ufi.ascq == 0)) ?
2022                            STATUS_CMD_OK : STATUS_CMD_FAILED);
2023
2024                        sc->sc_transfer.ccb = NULL;
2025
2026                        sc->sc_last_xfer_index = UMASS_T_CBI_COMMAND;
2027
2028                        (sc->sc_transfer.callback)
2029                            (sc, ccb, residue, status);
2030
2031                        break;
2032
2033                } else {
2034
2035                        /* Command Interrupt Data Block */
2036
2037                        DPRINTF(sc, UDMASS_CBI, "type=0x%02x, value=0x%02x\n",
2038                            sc->sbl.common.type, sc->sbl.common.value);
2039
2040                        if (sc->sbl.common.type == IDB_TYPE_CCI) {
2041
2042                                status = (sc->sbl.common.value & IDB_VALUE_STATUS_MASK);
2043
2044                                status = ((status == IDB_VALUE_PASS) ? STATUS_CMD_OK :
2045                                    (status == IDB_VALUE_FAIL) ? STATUS_CMD_FAILED :
2046                                    (status == IDB_VALUE_PERSISTENT) ? STATUS_CMD_FAILED :
2047                                    STATUS_WIRE_FAILED);
2048
2049                                sc->sc_transfer.ccb = NULL;
2050
2051                                sc->sc_last_xfer_index = UMASS_T_CBI_COMMAND;
2052
2053                                (sc->sc_transfer.callback)
2054                                    (sc, ccb, residue, status);
2055
2056                                break;
2057                        }
2058                }
2059
2060                /* fallthrough */
2061
2062        case USB_ST_SETUP:
2063tr_setup:
2064                usbd_xfer_set_frame_len(xfer, 0, usbd_xfer_max_len(xfer));
2065                usbd_transfer_submit(xfer);
2066                break;
2067
2068        default:                        /* Error */
2069                DPRINTF(sc, UDMASS_CBI, "Failed to read CSW: %s\n",
2070                    usbd_errstr(error));
2071                umass_tr_error(xfer, error);
2072                break;
2073        }
2074}
2075
2076/*
2077 * CAM specific functions (used by SCSI, UFI, 8070i (ATAPI))
2078 */
2079
2080static int
2081umass_cam_attach_sim(struct umass_softc *sc)
2082{
2083        struct cam_devq *devq;          /* Per device Queue */
2084
2085        /*
2086         * A HBA is attached to the CAM layer.
2087         *
2088         * The CAM layer will then after a while start probing for devices on
2089         * the bus. The number of SIMs is limited to one.
2090         */
2091
2092        devq = cam_simq_alloc(1 /* maximum openings */ );
2093        if (devq == NULL) {
2094                return (ENOMEM);
2095        }
2096        sc->sc_sim = cam_sim_alloc
2097            (&umass_cam_action, &umass_cam_poll,
2098            DEVNAME_SIM,
2099            sc /* priv */ ,
2100            sc->sc_unit /* unit number */ ,
2101            &sc->sc_mtx /* mutex */ ,
2102            1 /* maximum device openings */ ,
2103            0 /* maximum tagged device openings */ ,
2104            devq);
2105
2106        if (sc->sc_sim == NULL) {
2107                cam_simq_free(devq);
2108                return (ENOMEM);
2109        }
2110
2111        mtx_lock(&sc->sc_mtx);
2112
2113        if (xpt_bus_register(sc->sc_sim, sc->sc_dev,
2114            sc->sc_unit) != CAM_SUCCESS) {
2115                mtx_unlock(&sc->sc_mtx);
2116                return (ENOMEM);
2117        }
2118        mtx_unlock(&sc->sc_mtx);
2119
2120        return (0);
2121}
2122
2123#ifndef __rtems__
2124static void
2125umass_cam_attach(struct umass_softc *sc)
2126{
2127#ifndef USB_DEBUG
2128        if (bootverbose)
2129#endif
2130                printf("%s:%d:%d: Attached to scbus%d\n",
2131                    sc->sc_name, cam_sim_path(sc->sc_sim),
2132                    sc->sc_unit, cam_sim_path(sc->sc_sim));
2133}
2134#endif /* __rtems__ */
2135
2136/* umass_cam_detach
2137 *      detach from the CAM layer
2138 */
2139
2140static void
2141umass_cam_detach_sim(struct umass_softc *sc)
2142{
2143        if (sc->sc_sim != NULL) {
2144                if (xpt_bus_deregister(cam_sim_path(sc->sc_sim))) {
2145                        /* accessing the softc is not possible after this */
2146                        sc->sc_sim->softc = NULL;
2147                        cam_sim_free(sc->sc_sim, /* free_devq */ TRUE);
2148                } else {
2149                        panic("%s: CAM layer is busy\n",
2150                            sc->sc_name);
2151                }
2152                sc->sc_sim = NULL;
2153        }
2154}
2155
2156/* umass_cam_action
2157 *      CAM requests for action come through here
2158 */
2159
2160static void
2161umass_cam_action(struct cam_sim *sim, union ccb *ccb)
2162{
2163        struct umass_softc *sc = (struct umass_softc *)sim->softc;
2164
2165        if (sc == NULL) {
2166                ccb->ccb_h.status = CAM_SEL_TIMEOUT;
2167                xpt_done(ccb);
2168                return;
2169        }
2170
2171        /* Perform the requested action */
2172        switch (ccb->ccb_h.func_code) {
2173        case XPT_SCSI_IO:
2174                {
2175                        uint8_t *cmd;
2176                        uint8_t dir;
2177
2178                        if (ccb->csio.ccb_h.flags & CAM_CDB_POINTER) {
2179                                cmd = (uint8_t *)(ccb->csio.cdb_io.cdb_ptr);
2180                        } else {
2181                                cmd = (uint8_t *)(ccb->csio.cdb_io.cdb_bytes);
2182                        }
2183
2184                        DPRINTF(sc, UDMASS_SCSI, "%d:%d:%jx:XPT_SCSI_IO: "
2185                            "cmd: 0x%02x, flags: 0x%02x, "
2186                            "%db cmd/%db data/%db sense\n",
2187                            cam_sim_path(sc->sc_sim), ccb->ccb_h.target_id,
2188                            (uintmax_t)ccb->ccb_h.target_lun, cmd[0],
2189                            ccb->ccb_h.flags & CAM_DIR_MASK, ccb->csio.cdb_len,
2190                            ccb->csio.dxfer_len, ccb->csio.sense_len);
2191
2192                        if (sc->sc_transfer.ccb) {
2193                                DPRINTF(sc, UDMASS_SCSI, "%d:%d:%jx:XPT_SCSI_IO: "
2194                                    "I/O in progress, deferring\n",
2195                                    cam_sim_path(sc->sc_sim), ccb->ccb_h.target_id,
2196                                    (uintmax_t)ccb->ccb_h.target_lun);
2197                                ccb->ccb_h.status = CAM_SCSI_BUSY;
2198                                xpt_done(ccb);
2199                                goto done;
2200                        }
2201                        switch (ccb->ccb_h.flags & CAM_DIR_MASK) {
2202                        case CAM_DIR_IN:
2203                                dir = DIR_IN;
2204                                break;
2205                        case CAM_DIR_OUT:
2206                                dir = DIR_OUT;
2207                                DIF(UDMASS_SCSI,
2208                                    umass_dump_buffer(sc, ccb->csio.data_ptr,
2209                                    ccb->csio.dxfer_len, 48));
2210                                break;
2211                        default:
2212                                dir = DIR_NONE;
2213                        }
2214
2215                        ccb->ccb_h.status = CAM_REQ_INPROG | CAM_SIM_QUEUED;
2216
2217                        /*
2218                         * sc->sc_transform will convert the command to the
2219                         * command format needed by the specific command set
2220                         * and return the converted command in
2221                         * "sc->sc_transfer.cmd_data"
2222                         */
2223                        if (umass_std_transform(sc, ccb, cmd, ccb->csio.cdb_len)) {
2224
2225                                if (sc->sc_transfer.cmd_data[0] == INQUIRY) {
2226                                        const char *pserial;
2227
2228                                        pserial = usb_get_serial(sc->sc_udev);
2229
2230                                        /*
2231                                         * Umass devices don't generally report their serial numbers
2232                                         * in the usual SCSI way.  Emulate it here.
2233                                         */
2234                                        if ((sc->sc_transfer.cmd_data[1] & SI_EVPD) &&
2235                                            (sc->sc_transfer.cmd_data[2] == SVPD_UNIT_SERIAL_NUMBER) &&
2236                                            (pserial[0] != '\0')) {
2237                                                struct scsi_vpd_unit_serial_number *vpd_serial;
2238
2239                                                vpd_serial = (struct scsi_vpd_unit_serial_number *)ccb->csio.data_ptr;
2240                                                vpd_serial->length = strlen(pserial);
2241                                                if (vpd_serial->length > sizeof(vpd_serial->serial_num))
2242                                                        vpd_serial->length = sizeof(vpd_serial->serial_num);
2243                                                memcpy(vpd_serial->serial_num, pserial, vpd_serial->length);
2244                                                ccb->csio.scsi_status = SCSI_STATUS_OK;
2245                                                ccb->ccb_h.status = CAM_REQ_CMP;
2246                                                xpt_done(ccb);
2247                                                goto done;
2248                                        }
2249
2250                                        /*
2251                                         * Handle EVPD inquiry for broken devices first
2252                                         * NO_INQUIRY also implies NO_INQUIRY_EVPD
2253                                         */
2254                                        if ((sc->sc_quirks & (NO_INQUIRY_EVPD | NO_INQUIRY)) &&
2255                                            (sc->sc_transfer.cmd_data[1] & SI_EVPD)) {
2256
2257                                                scsi_set_sense_data(&ccb->csio.sense_data,
2258                                                        /*sense_format*/ SSD_TYPE_NONE,
2259                                                        /*current_error*/ 1,
2260                                                        /*sense_key*/ SSD_KEY_ILLEGAL_REQUEST,
2261                                                        /*asc*/ 0x24,
2262                                                        /*ascq*/ 0x00,
2263                                                        /*extra args*/ SSD_ELEM_NONE);
2264                                                ccb->csio.scsi_status = SCSI_STATUS_CHECK_COND;
2265                                                ccb->ccb_h.status =
2266                                                    CAM_SCSI_STATUS_ERROR |
2267                                                    CAM_AUTOSNS_VALID |
2268                                                    CAM_DEV_QFRZN;
2269                                                xpt_freeze_devq(ccb->ccb_h.path, 1);
2270                                                xpt_done(ccb);
2271                                                goto done;
2272                                        }
2273                                        /*
2274                                         * Return fake inquiry data for
2275                                         * broken devices
2276                                         */
2277                                        if (sc->sc_quirks & NO_INQUIRY) {
2278                                                memcpy(ccb->csio.data_ptr, &fake_inq_data,
2279                                                    sizeof(fake_inq_data));
2280                                                ccb->csio.scsi_status = SCSI_STATUS_OK;
2281                                                ccb->ccb_h.status = CAM_REQ_CMP;
2282                                                xpt_done(ccb);
2283                                                goto done;
2284                                        }
2285                                        if (sc->sc_quirks & FORCE_SHORT_INQUIRY) {
2286                                                ccb->csio.dxfer_len = SHORT_INQUIRY_LENGTH;
2287                                        }
2288                                } else if (sc->sc_transfer.cmd_data[0] == PREVENT_ALLOW) {
2289                                        if (sc->sc_quirks & NO_PREVENT_ALLOW) {
2290                                                ccb->csio.scsi_status = SCSI_STATUS_OK;
2291                                                ccb->ccb_h.status = CAM_REQ_CMP;
2292                                                xpt_done(ccb);
2293                                                goto done;
2294                                        }
2295                                } else if (sc->sc_transfer.cmd_data[0] == SYNCHRONIZE_CACHE) {
2296                                        if (sc->sc_quirks & NO_SYNCHRONIZE_CACHE) {
2297                                                ccb->csio.scsi_status = SCSI_STATUS_OK;
2298                                                ccb->ccb_h.status = CAM_REQ_CMP;
2299                                                xpt_done(ccb);
2300                                                goto done;
2301                                        }
2302                                }
2303                                umass_command_start(sc, dir, ccb->csio.data_ptr,
2304                                    ccb->csio.dxfer_len,
2305                                    ccb->ccb_h.timeout,
2306                                    &umass_cam_cb, ccb);
2307                        }
2308                        break;
2309                }
2310        case XPT_PATH_INQ:
2311                {
2312                        struct ccb_pathinq *cpi = &ccb->cpi;
2313
2314                        DPRINTF(sc, UDMASS_SCSI, "%d:%d:%jx:XPT_PATH_INQ:.\n",
2315                            sc ? cam_sim_path(sc->sc_sim) : -1, ccb->ccb_h.target_id,
2316                            (uintmax_t)ccb->ccb_h.target_lun);
2317
2318                        /* host specific information */
2319                        cpi->version_num = 1;
2320                        cpi->hba_inquiry = 0;
2321                        cpi->target_sprt = 0;
2322                        cpi->hba_misc = PIM_NO_6_BYTE;
2323                        cpi->hba_eng_cnt = 0;
2324                        cpi->max_target = UMASS_SCSIID_MAX;     /* one target */
2325                        cpi->initiator_id = UMASS_SCSIID_HOST;
2326                        strlcpy(cpi->sim_vid, "FreeBSD", SIM_IDLEN);
2327                        strlcpy(cpi->hba_vid, "USB SCSI", HBA_IDLEN);
2328                        strlcpy(cpi->dev_name, cam_sim_name(sim), DEV_IDLEN);
2329                        cpi->unit_number = cam_sim_unit(sim);
2330                        cpi->bus_id = sc->sc_unit;
2331                        cpi->protocol = PROTO_SCSI;
2332                        cpi->protocol_version = SCSI_REV_2;
2333                        cpi->transport = XPORT_USB;
2334                        cpi->transport_version = 0;
2335
2336                        if (sc == NULL) {
2337                                cpi->base_transfer_speed = 0;
2338                                cpi->max_lun = 0;
2339                        } else {
2340                                if (sc->sc_quirks & FLOPPY_SPEED) {
2341                                        cpi->base_transfer_speed =
2342                                            UMASS_FLOPPY_TRANSFER_SPEED;
2343                                } else {
2344                                        switch (usbd_get_speed(sc->sc_udev)) {
2345                                        case USB_SPEED_SUPER:
2346                                                cpi->base_transfer_speed =
2347                                                    UMASS_SUPER_TRANSFER_SPEED;
2348                                                cpi->maxio = MAXPHYS;
2349                                                break;
2350                                        case USB_SPEED_HIGH:
2351                                                cpi->base_transfer_speed =
2352                                                    UMASS_HIGH_TRANSFER_SPEED;
2353                                                break;
2354                                        default:
2355                                                cpi->base_transfer_speed =
2356                                                    UMASS_FULL_TRANSFER_SPEED;
2357                                                break;
2358                                        }
2359                                }
2360                                cpi->max_lun = sc->sc_maxlun;
2361                        }
2362
2363                        cpi->ccb_h.status = CAM_REQ_CMP;
2364                        xpt_done(ccb);
2365                        break;
2366                }
2367        case XPT_RESET_DEV:
2368                {
2369                        DPRINTF(sc, UDMASS_SCSI, "%d:%d:%jx:XPT_RESET_DEV:.\n",
2370                            cam_sim_path(sc->sc_sim), ccb->ccb_h.target_id,
2371                            (uintmax_t)ccb->ccb_h.target_lun);
2372
2373                        umass_reset(sc);
2374
2375                        ccb->ccb_h.status = CAM_REQ_CMP;
2376                        xpt_done(ccb);
2377                        break;
2378                }
2379        case XPT_GET_TRAN_SETTINGS:
2380                {
2381                        struct ccb_trans_settings *cts = &ccb->cts;
2382
2383                        DPRINTF(sc, UDMASS_SCSI, "%d:%d:%jx:XPT_GET_TRAN_SETTINGS:.\n",
2384                            cam_sim_path(sc->sc_sim), ccb->ccb_h.target_id,
2385                            (uintmax_t)ccb->ccb_h.target_lun);
2386
2387                        cts->protocol = PROTO_SCSI;
2388                        cts->protocol_version = SCSI_REV_2;
2389                        cts->transport = XPORT_USB;
2390                        cts->transport_version = 0;
2391                        cts->xport_specific.valid = 0;
2392
2393                        ccb->ccb_h.status = CAM_REQ_CMP;
2394                        xpt_done(ccb);
2395                        break;
2396                }
2397        case XPT_SET_TRAN_SETTINGS:
2398                {
2399                        DPRINTF(sc, UDMASS_SCSI, "%d:%d:%jx:XPT_SET_TRAN_SETTINGS:.\n",
2400                            cam_sim_path(sc->sc_sim), ccb->ccb_h.target_id,
2401                            (uintmax_t)ccb->ccb_h.target_lun);
2402
2403                        ccb->ccb_h.status = CAM_FUNC_NOTAVAIL;
2404                        xpt_done(ccb);
2405                        break;
2406                }
2407#ifndef __rtems__
2408        case XPT_CALC_GEOMETRY:
2409                {
2410                        cam_calc_geometry(&ccb->ccg, /* extended */ 1);
2411                        xpt_done(ccb);
2412                        break;
2413                }
2414#endif /* __rtems__ */
2415        case XPT_NOOP:
2416                {
2417                        DPRINTF(sc, UDMASS_SCSI, "%d:%d:%jx:XPT_NOOP:.\n",
2418                            sc ? cam_sim_path(sc->sc_sim) : -1, ccb->ccb_h.target_id,
2419                            (uintmax_t)ccb->ccb_h.target_lun);
2420
2421                        ccb->ccb_h.status = CAM_REQ_CMP;
2422                        xpt_done(ccb);
2423                        break;
2424                }
2425        default:
2426                DPRINTF(sc, UDMASS_SCSI, "%d:%d:%jx:func_code 0x%04x: "
2427                    "Not implemented\n",
2428                    sc ? cam_sim_path(sc->sc_sim) : -1, ccb->ccb_h.target_id,
2429                    (uintmax_t)ccb->ccb_h.target_lun, ccb->ccb_h.func_code);
2430
2431                ccb->ccb_h.status = CAM_FUNC_NOTAVAIL;
2432                xpt_done(ccb);
2433                break;
2434        }
2435
2436done:
2437        return;
2438}
2439
2440static void
2441umass_cam_poll(struct cam_sim *sim)
2442{
2443        struct umass_softc *sc = (struct umass_softc *)sim->softc;
2444
2445        if (sc == NULL)
2446                return;
2447
2448        DPRINTF(sc, UDMASS_SCSI, "CAM poll\n");
2449
2450        usbd_transfer_poll(sc->sc_xfer, UMASS_T_MAX);
2451}
2452
2453
2454/* umass_cam_cb
2455 *      finalise a completed CAM command
2456 */
2457
2458static void
2459umass_cam_cb(struct umass_softc *sc, union ccb *ccb, uint32_t residue,
2460    uint8_t status)
2461{
2462        ccb->csio.resid = residue;
2463
2464        switch (status) {
2465        case STATUS_CMD_OK:
2466                ccb->ccb_h.status = CAM_REQ_CMP;
2467                if ((sc->sc_quirks & READ_CAPACITY_OFFBY1) &&
2468                    (ccb->ccb_h.func_code == XPT_SCSI_IO) &&
2469                    (ccb->csio.cdb_io.cdb_bytes[0] == READ_CAPACITY)) {
2470                        struct scsi_read_capacity_data *rcap;
2471                        uint32_t maxsector;
2472
2473                        rcap = (void *)(ccb->csio.data_ptr);
2474                        maxsector = scsi_4btoul(rcap->addr) - 1;
2475                        scsi_ulto4b(maxsector, rcap->addr);
2476                }
2477                /*
2478                 * We have to add SVPD_UNIT_SERIAL_NUMBER to the list
2479                 * of pages supported by the device - otherwise, CAM
2480                 * will never ask us for the serial number if the
2481                 * device cannot handle that by itself.
2482                 */
2483                if (ccb->ccb_h.func_code == XPT_SCSI_IO &&
2484                    sc->sc_transfer.cmd_data[0] == INQUIRY &&
2485                    (sc->sc_transfer.cmd_data[1] & SI_EVPD) &&
2486                    sc->sc_transfer.cmd_data[2] == SVPD_SUPPORTED_PAGE_LIST &&
2487                    (usb_get_serial(sc->sc_udev)[0] != '\0')) {
2488                        struct ccb_scsiio *csio;
2489                        struct scsi_vpd_supported_page_list *page_list;
2490
2491                        csio = &ccb->csio;
2492                        page_list = (struct scsi_vpd_supported_page_list *)csio->data_ptr;
2493                        if (page_list->length + 1 < SVPD_SUPPORTED_PAGES_SIZE) {
2494                                page_list->list[page_list->length] = SVPD_UNIT_SERIAL_NUMBER;
2495                                page_list->length++;
2496                        }
2497                }
2498                xpt_done(ccb);
2499                break;
2500
2501        case STATUS_CMD_UNKNOWN:
2502        case STATUS_CMD_FAILED:
2503
2504                /* fetch sense data */
2505
2506                /* the rest of the command was filled in at attach */
2507                sc->cam_scsi_sense.length = ccb->csio.sense_len;
2508
2509                DPRINTF(sc, UDMASS_SCSI, "Fetching %d bytes of "
2510                    "sense data\n", ccb->csio.sense_len);
2511
2512                if (umass_std_transform(sc, ccb, &sc->cam_scsi_sense.opcode,
2513                    sizeof(sc->cam_scsi_sense))) {
2514
2515                        if ((sc->sc_quirks & FORCE_SHORT_INQUIRY) &&
2516                            (sc->sc_transfer.cmd_data[0] == INQUIRY)) {
2517                                ccb->csio.sense_len = SHORT_INQUIRY_LENGTH;
2518                        }
2519                        umass_command_start(sc, DIR_IN, &ccb->csio.sense_data.error_code,
2520                            ccb->csio.sense_len, ccb->ccb_h.timeout,
2521                            &umass_cam_sense_cb, ccb);
2522                }
2523                break;
2524
2525        default:
2526                /*
2527                 * The wire protocol failed and will hopefully have
2528                 * recovered. We return an error to CAM and let CAM
2529                 * retry the command if necessary.
2530                 */
2531                xpt_freeze_devq(ccb->ccb_h.path, 1);
2532                ccb->ccb_h.status = CAM_REQ_CMP_ERR | CAM_DEV_QFRZN;
2533                xpt_done(ccb);
2534                break;
2535        }
2536}
2537
2538/*
2539 * Finalise a completed autosense operation
2540 */
2541static void
2542umass_cam_sense_cb(struct umass_softc *sc, union ccb *ccb, uint32_t residue,
2543    uint8_t status)
2544{
2545        uint8_t *cmd;
2546
2547        switch (status) {
2548        case STATUS_CMD_OK:
2549        case STATUS_CMD_UNKNOWN:
2550        case STATUS_CMD_FAILED: {
2551                int key, sense_len;
2552
2553                ccb->csio.sense_resid = residue;
2554                sense_len = ccb->csio.sense_len - ccb->csio.sense_resid;
2555                key = scsi_get_sense_key(&ccb->csio.sense_data, sense_len,
2556                                         /*show_errors*/ 1);
2557
2558                if (ccb->csio.ccb_h.flags & CAM_CDB_POINTER) {
2559                        cmd = (uint8_t *)(ccb->csio.cdb_io.cdb_ptr);
2560                } else {
2561                        cmd = (uint8_t *)(ccb->csio.cdb_io.cdb_bytes);
2562                }
2563
2564                /*
2565                 * Getting sense data always succeeds (apart from wire
2566                 * failures):
2567                 */
2568                if ((sc->sc_quirks & RS_NO_CLEAR_UA) &&
2569                    (cmd[0] == INQUIRY) &&
2570                    (key == SSD_KEY_UNIT_ATTENTION)) {
2571                        /*
2572                         * Ignore unit attention errors in the case where
2573                         * the Unit Attention state is not cleared on
2574                         * REQUEST SENSE. They will appear again at the next
2575                         * command.
2576                         */
2577                        ccb->ccb_h.status = CAM_REQ_CMP;
2578                } else if (key == SSD_KEY_NO_SENSE) {
2579                        /*
2580                         * No problem after all (in the case of CBI without
2581                         * CCI)
2582                         */
2583                        ccb->ccb_h.status = CAM_REQ_CMP;
2584                } else if ((sc->sc_quirks & RS_NO_CLEAR_UA) &&
2585                            (cmd[0] == READ_CAPACITY) &&
2586                    (key == SSD_KEY_UNIT_ATTENTION)) {
2587                        /*
2588                         * Some devices do not clear the unit attention error
2589                         * on request sense. We insert a test unit ready
2590                         * command to make sure we clear the unit attention
2591                         * condition, then allow the retry to proceed as
2592                         * usual.
2593                         */
2594
2595                        xpt_freeze_devq(ccb->ccb_h.path, 1);
2596                        ccb->ccb_h.status = CAM_SCSI_STATUS_ERROR
2597                            | CAM_AUTOSNS_VALID | CAM_DEV_QFRZN;
2598                        ccb->csio.scsi_status = SCSI_STATUS_CHECK_COND;
2599
2600#if 0
2601                        DELAY(300000);
2602#endif
2603                        DPRINTF(sc, UDMASS_SCSI, "Doing a sneaky"
2604                            "TEST_UNIT_READY\n");
2605
2606                        /* the rest of the command was filled in at attach */
2607
2608                        if ((sc->sc_transform)(sc,
2609                            &sc->cam_scsi_test_unit_ready.opcode,
2610                            sizeof(sc->cam_scsi_test_unit_ready)) == 1) {
2611                                umass_command_start(sc, DIR_NONE, NULL, 0,
2612                                    ccb->ccb_h.timeout,
2613                                    &umass_cam_quirk_cb, ccb);
2614                                break;
2615                        }
2616                } else {
2617                        xpt_freeze_devq(ccb->ccb_h.path, 1);
2618                        if (key >= 0) {
2619                                ccb->ccb_h.status = CAM_SCSI_STATUS_ERROR
2620                                    | CAM_AUTOSNS_VALID | CAM_DEV_QFRZN;
2621                                ccb->csio.scsi_status = SCSI_STATUS_CHECK_COND;
2622                        } else
2623                                ccb->ccb_h.status = CAM_AUTOSENSE_FAIL
2624                                    | CAM_DEV_QFRZN;
2625                }
2626                xpt_done(ccb);
2627                break;
2628        }
2629        default:
2630                DPRINTF(sc, UDMASS_SCSI, "Autosense failed, "
2631                    "status %d\n", status);
2632                xpt_freeze_devq(ccb->ccb_h.path, 1);
2633                ccb->ccb_h.status = CAM_AUTOSENSE_FAIL | CAM_DEV_QFRZN;
2634                xpt_done(ccb);
2635        }
2636}
2637
2638/*
2639 * This completion code just handles the fact that we sent a test-unit-ready
2640 * after having previously failed a READ CAPACITY with CHECK_COND.  The CCB
2641 * status for CAM is already set earlier.
2642 */
2643static void
2644umass_cam_quirk_cb(struct umass_softc *sc, union ccb *ccb, uint32_t residue,
2645    uint8_t status)
2646{
2647        DPRINTF(sc, UDMASS_SCSI, "Test unit ready "
2648            "returned status %d\n", status);
2649
2650        xpt_done(ccb);
2651}
2652
2653/*
2654 * SCSI specific functions
2655 */
2656
2657static uint8_t
2658umass_scsi_transform(struct umass_softc *sc, uint8_t *cmd_ptr,
2659    uint8_t cmd_len)
2660{
2661        if ((cmd_len == 0) ||
2662            (cmd_len > sizeof(sc->sc_transfer.cmd_data))) {
2663                DPRINTF(sc, UDMASS_SCSI, "Invalid command "
2664                    "length: %d bytes\n", cmd_len);
2665                return (0);             /* failure */
2666        }
2667        sc->sc_transfer.cmd_len = cmd_len;
2668
2669        switch (cmd_ptr[0]) {
2670        case TEST_UNIT_READY:
2671                if (sc->sc_quirks & NO_TEST_UNIT_READY) {
2672                        DPRINTF(sc, UDMASS_SCSI, "Converted TEST_UNIT_READY "
2673                            "to START_UNIT\n");
2674                        memset(sc->sc_transfer.cmd_data, 0, cmd_len);
2675                        sc->sc_transfer.cmd_data[0] = START_STOP_UNIT;
2676                        sc->sc_transfer.cmd_data[4] = SSS_START;
2677                        return (1);
2678                }
2679                break;
2680
2681        case INQUIRY:
2682                /*
2683                 * some drives wedge when asked for full inquiry
2684                 * information.
2685                 */
2686                if (sc->sc_quirks & FORCE_SHORT_INQUIRY) {
2687                        memcpy(sc->sc_transfer.cmd_data, cmd_ptr, cmd_len);
2688                        sc->sc_transfer.cmd_data[4] = SHORT_INQUIRY_LENGTH;
2689                        return (1);
2690                }
2691                break;
2692        }
2693
2694        memcpy(sc->sc_transfer.cmd_data, cmd_ptr, cmd_len);
2695        return (1);
2696}
2697
2698static uint8_t
2699umass_rbc_transform(struct umass_softc *sc, uint8_t *cmd_ptr, uint8_t cmd_len)
2700{
2701        if ((cmd_len == 0) ||
2702            (cmd_len > sizeof(sc->sc_transfer.cmd_data))) {
2703                DPRINTF(sc, UDMASS_SCSI, "Invalid command "
2704                    "length: %d bytes\n", cmd_len);
2705                return (0);             /* failure */
2706        }
2707        switch (cmd_ptr[0]) {
2708                /* these commands are defined in RBC: */
2709        case READ_10:
2710        case READ_CAPACITY:
2711        case START_STOP_UNIT:
2712        case SYNCHRONIZE_CACHE:
2713        case WRITE_10:
2714        case VERIFY_10:
2715        case INQUIRY:
2716        case MODE_SELECT_10:
2717        case MODE_SENSE_10:
2718        case TEST_UNIT_READY:
2719        case WRITE_BUFFER:
2720                /*
2721                 * The following commands are not listed in my copy of the
2722                 * RBC specs. CAM however seems to want those, and at least
2723                 * the Sony DSC device appears to support those as well
2724                 */
2725        case REQUEST_SENSE:
2726        case PREVENT_ALLOW:
2727
2728                memcpy(sc->sc_transfer.cmd_data, cmd_ptr, cmd_len);
2729
2730                if ((sc->sc_quirks & RBC_PAD_TO_12) && (cmd_len < 12)) {
2731                        memset(sc->sc_transfer.cmd_data + cmd_len,
2732                            0, 12 - cmd_len);
2733                        cmd_len = 12;
2734                }
2735                sc->sc_transfer.cmd_len = cmd_len;
2736                return (1);             /* success */
2737
2738                /* All other commands are not legal in RBC */
2739        default:
2740                DPRINTF(sc, UDMASS_SCSI, "Unsupported RBC "
2741                    "command 0x%02x\n", cmd_ptr[0]);
2742                return (0);             /* failure */
2743        }
2744}
2745
2746static uint8_t
2747umass_ufi_transform(struct umass_softc *sc, uint8_t *cmd_ptr,
2748    uint8_t cmd_len)
2749{
2750        if ((cmd_len == 0) ||
2751            (cmd_len > sizeof(sc->sc_transfer.cmd_data))) {
2752                DPRINTF(sc, UDMASS_SCSI, "Invalid command "
2753                    "length: %d bytes\n", cmd_len);
2754                return (0);             /* failure */
2755        }
2756        /* An UFI command is always 12 bytes in length */
2757        sc->sc_transfer.cmd_len = UFI_COMMAND_LENGTH;
2758
2759        /* Zero the command data */
2760        memset(sc->sc_transfer.cmd_data, 0, UFI_COMMAND_LENGTH);
2761
2762        switch (cmd_ptr[0]) {
2763                /*
2764                 * Commands of which the format has been verified. They
2765                 * should work. Copy the command into the (zeroed out)
2766                 * destination buffer.
2767                 */
2768        case TEST_UNIT_READY:
2769                if (sc->sc_quirks & NO_TEST_UNIT_READY) {
2770                        /*
2771                         * Some devices do not support this command. Start
2772                         * Stop Unit should give the same results
2773                         */
2774                        DPRINTF(sc, UDMASS_UFI, "Converted TEST_UNIT_READY "
2775                            "to START_UNIT\n");
2776
2777                        sc->sc_transfer.cmd_data[0] = START_STOP_UNIT;
2778                        sc->sc_transfer.cmd_data[4] = SSS_START;
2779                        return (1);
2780                }
2781                break;
2782
2783        case REZERO_UNIT:
2784        case REQUEST_SENSE:
2785        case FORMAT_UNIT:
2786        case INQUIRY:
2787        case START_STOP_UNIT:
2788        case SEND_DIAGNOSTIC:
2789        case PREVENT_ALLOW:
2790        case READ_CAPACITY:
2791        case READ_10:
2792        case WRITE_10:
2793        case POSITION_TO_ELEMENT:       /* SEEK_10 */
2794        case WRITE_AND_VERIFY:
2795        case VERIFY:
2796        case MODE_SELECT_10:
2797        case MODE_SENSE_10:
2798        case READ_12:
2799        case WRITE_12:
2800        case READ_FORMAT_CAPACITIES:
2801                break;
2802
2803                /*
2804                 * SYNCHRONIZE_CACHE isn't supported by UFI, nor should it be
2805                 * required for UFI devices, so it is appropriate to fake
2806                 * success.
2807                 */
2808        case SYNCHRONIZE_CACHE:
2809                return (2);
2810
2811        default:
2812                DPRINTF(sc, UDMASS_SCSI, "Unsupported UFI "
2813                    "command 0x%02x\n", cmd_ptr[0]);
2814                return (0);             /* failure */
2815        }
2816
2817        memcpy(sc->sc_transfer.cmd_data, cmd_ptr, cmd_len);
2818        return (1);                     /* success */
2819}
2820
2821/*
2822 * 8070i (ATAPI) specific functions
2823 */
2824static uint8_t
2825umass_atapi_transform(struct umass_softc *sc, uint8_t *cmd_ptr,
2826    uint8_t cmd_len)
2827{
2828        if ((cmd_len == 0) ||
2829            (cmd_len > sizeof(sc->sc_transfer.cmd_data))) {
2830                DPRINTF(sc, UDMASS_SCSI, "Invalid command "
2831                    "length: %d bytes\n", cmd_len);
2832                return (0);             /* failure */
2833        }
2834        /* An ATAPI command is always 12 bytes in length. */
2835        sc->sc_transfer.cmd_len = ATAPI_COMMAND_LENGTH;
2836
2837        /* Zero the command data */
2838        memset(sc->sc_transfer.cmd_data, 0, ATAPI_COMMAND_LENGTH);
2839
2840        switch (cmd_ptr[0]) {
2841                /*
2842                 * Commands of which the format has been verified. They
2843                 * should work. Copy the command into the destination
2844                 * buffer.
2845                 */
2846        case INQUIRY:
2847                /*
2848                 * some drives wedge when asked for full inquiry
2849                 * information.
2850                 */
2851                if (sc->sc_quirks & FORCE_SHORT_INQUIRY) {
2852                        memcpy(sc->sc_transfer.cmd_data, cmd_ptr, cmd_len);
2853
2854                        sc->sc_transfer.cmd_data[4] = SHORT_INQUIRY_LENGTH;
2855                        return (1);
2856                }
2857                break;
2858
2859        case TEST_UNIT_READY:
2860                if (sc->sc_quirks & NO_TEST_UNIT_READY) {
2861                        DPRINTF(sc, UDMASS_SCSI, "Converted TEST_UNIT_READY "
2862                            "to START_UNIT\n");
2863                        sc->sc_transfer.cmd_data[0] = START_STOP_UNIT;
2864                        sc->sc_transfer.cmd_data[4] = SSS_START;
2865                        return (1);
2866                }
2867                break;
2868
2869        case REZERO_UNIT:
2870        case REQUEST_SENSE:
2871        case START_STOP_UNIT:
2872        case SEND_DIAGNOSTIC:
2873        case PREVENT_ALLOW:
2874        case READ_CAPACITY:
2875        case READ_10:
2876        case WRITE_10:
2877        case POSITION_TO_ELEMENT:       /* SEEK_10 */
2878        case SYNCHRONIZE_CACHE:
2879        case MODE_SELECT_10:
2880        case MODE_SENSE_10:
2881        case READ_BUFFER:
2882        case 0x42:                      /* READ_SUBCHANNEL */
2883        case 0x43:                      /* READ_TOC */
2884        case 0x44:                      /* READ_HEADER */
2885        case 0x47:                      /* PLAY_MSF (Play Minute/Second/Frame) */
2886        case 0x48:                      /* PLAY_TRACK */
2887        case 0x49:                      /* PLAY_TRACK_REL */
2888        case 0x4b:                      /* PAUSE */
2889        case 0x51:                      /* READ_DISK_INFO */
2890        case 0x52:                      /* READ_TRACK_INFO */
2891        case 0x54:                      /* SEND_OPC */
2892        case 0x59:                      /* READ_MASTER_CUE */
2893        case 0x5b:                      /* CLOSE_TR_SESSION */
2894        case 0x5c:                      /* READ_BUFFER_CAP */
2895        case 0x5d:                      /* SEND_CUE_SHEET */
2896        case 0xa1:                      /* BLANK */
2897        case 0xa5:                      /* PLAY_12 */
2898        case 0xa6:                      /* EXCHANGE_MEDIUM */
2899        case 0xad:                      /* READ_DVD_STRUCTURE */
2900        case 0xbb:                      /* SET_CD_SPEED */
2901        case 0xe5:                      /* READ_TRACK_INFO_PHILIPS */
2902                break;
2903
2904        case READ_12:
2905        case WRITE_12:
2906        default:
2907                DPRINTF(sc, UDMASS_SCSI, "Unsupported ATAPI "
2908                    "command 0x%02x - trying anyway\n",
2909                    cmd_ptr[0]);
2910                break;
2911        }
2912
2913        memcpy(sc->sc_transfer.cmd_data, cmd_ptr, cmd_len);
2914        return (1);                     /* success */
2915}
2916
2917static uint8_t
2918umass_no_transform(struct umass_softc *sc, uint8_t *cmd,
2919    uint8_t cmdlen)
2920{
2921        return (0);                     /* failure */
2922}
2923
2924static uint8_t
2925umass_std_transform(struct umass_softc *sc, union ccb *ccb,
2926    uint8_t *cmd, uint8_t cmdlen)
2927{
2928        uint8_t retval;
2929
2930        retval = (sc->sc_transform) (sc, cmd, cmdlen);
2931
2932        if (retval == 2) {
2933                ccb->ccb_h.status = CAM_REQ_CMP;
2934                xpt_done(ccb);
2935                return (0);
2936        } else if (retval == 0) {
2937                xpt_freeze_devq(ccb->ccb_h.path, 1);
2938                ccb->ccb_h.status = CAM_REQ_INVALID | CAM_DEV_QFRZN;
2939                xpt_done(ccb);
2940                return (0);
2941        }
2942        /* Command should be executed */
2943        return (1);
2944}
2945
2946#ifdef USB_DEBUG
2947static void
2948umass_bbb_dump_cbw(struct umass_softc *sc, umass_bbb_cbw_t *cbw)
2949{
2950        uint8_t *c = cbw->CBWCDB;
2951
2952        uint32_t dlen = UGETDW(cbw->dCBWDataTransferLength);
2953        uint32_t tag = UGETDW(cbw->dCBWTag);
2954
2955        uint8_t clen = cbw->bCDBLength;
2956        uint8_t flags = cbw->bCBWFlags;
2957        uint8_t lun = cbw->bCBWLUN;
2958
2959        DPRINTF(sc, UDMASS_BBB, "CBW %d: cmd = %db "
2960            "(0x%02x%02x%02x%02x%02x%02x%s), "
2961            "data = %db, lun = %d, dir = %s\n",
2962            tag, clen,
2963            c[0], c[1], c[2], c[3], c[4], c[5], (clen > 6 ? "..." : ""),
2964            dlen, lun, (flags == CBWFLAGS_IN ? "in" :
2965            (flags == CBWFLAGS_OUT ? "out" : "<invalid>")));
2966}
2967
2968static void
2969umass_bbb_dump_csw(struct umass_softc *sc, umass_bbb_csw_t *csw)
2970{
2971        uint32_t sig = UGETDW(csw->dCSWSignature);
2972        uint32_t tag = UGETDW(csw->dCSWTag);
2973        uint32_t res = UGETDW(csw->dCSWDataResidue);
2974        uint8_t status = csw->bCSWStatus;
2975
2976        DPRINTF(sc, UDMASS_BBB, "CSW %d: sig = 0x%08x (%s), tag = 0x%08x, "
2977            "res = %d, status = 0x%02x (%s)\n",
2978            tag, sig, (sig == CSWSIGNATURE ? "valid" : "invalid"),
2979            tag, res,
2980            status, (status == CSWSTATUS_GOOD ? "good" :
2981            (status == CSWSTATUS_FAILED ? "failed" :
2982            (status == CSWSTATUS_PHASE ? "phase" : "<invalid>"))));
2983}
2984
2985static void
2986umass_cbi_dump_cmd(struct umass_softc *sc, void *cmd, uint8_t cmdlen)
2987{
2988        uint8_t *c = cmd;
2989        uint8_t dir = sc->sc_transfer.dir;
2990
2991        DPRINTF(sc, UDMASS_BBB, "cmd = %db "
2992            "(0x%02x%02x%02x%02x%02x%02x%s), "
2993            "data = %db, dir = %s\n",
2994            cmdlen,
2995            c[0], c[1], c[2], c[3], c[4], c[5], (cmdlen > 6 ? "..." : ""),
2996            sc->sc_transfer.data_len,
2997            (dir == DIR_IN ? "in" :
2998            (dir == DIR_OUT ? "out" :
2999            (dir == DIR_NONE ? "no data phase" : "<invalid>"))));
3000}
3001
3002static void
3003umass_dump_buffer(struct umass_softc *sc, uint8_t *buffer, uint32_t buflen,
3004    uint32_t printlen)
3005{
3006        uint32_t i, j;
3007        char s1[40];
3008        char s2[40];
3009        char s3[5];
3010
3011        s1[0] = '\0';
3012        s3[0] = '\0';
3013
3014        sprintf(s2, " buffer=%p, buflen=%d", buffer, buflen);
3015        for (i = 0; (i < buflen) && (i < printlen); i++) {
3016                j = i % 16;
3017                if (j == 0 && i != 0) {
3018                        DPRINTF(sc, UDMASS_GEN, "0x %s%s\n",
3019                            s1, s2);
3020                        s2[0] = '\0';
3021                }
3022                sprintf(&s1[j * 2], "%02x", buffer[i] & 0xff);
3023        }
3024        if (buflen > printlen)
3025                sprintf(s3, " ...");
3026        DPRINTF(sc, UDMASS_GEN, "0x %s%s%s\n",
3027            s1, s2, s3);
3028}
3029
3030#endif
Note: See TracBrowser for help on using the repository browser.