Fix a few typos across the tree.
[dragonfly.git] / sys / bus / u4b / usb_msctest.c
1 /* $FreeBSD: head/sys/dev/usb/usb_msctest.c 269578 2014-08-05 09:59:16Z n_hibma $ */
2 /*-
3  * Copyright (c) 2008,2011 Hans Petter Selasky. All rights reserved.
4  *
5  * Redistribution and use in source and binary forms, with or without
6  * modification, are permitted provided that the following conditions
7  * are met:
8  * 1. Redistributions of source code must retain the above copyright
9  *    notice, this list of conditions and the following disclaimer.
10  * 2. Redistributions in binary form must reproduce the above copyright
11  *    notice, this list of conditions and the following disclaimer in the
12  *    documentation and/or other materials provided with the distribution.
13  *
14  * THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND
15  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
16  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
17  * ARE DISCLAIMED.  IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE
18  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
19  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
20  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
21  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
22  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
23  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
24  * SUCH DAMAGE.
25  */
26
27 /*
28  * The following file contains code that will detect USB autoinstall
29  * disks.
30  *
31  * TODO: Potentially we could add code to automatically detect USB
32  * mass storage quirks for not supported SCSI commands!
33  */
34
35 #include <sys/stdint.h>
36 #include <sys/param.h>
37 #include <sys/queue.h>
38 #include <sys/types.h>
39 #include <sys/systm.h>
40 #include <sys/kernel.h>
41 #include <sys/bus.h>
42 #include <sys/module.h>
43 #include <sys/lock.h>
44 #include <sys/mutex.h>
45 #include <sys/condvar.h>
46 #include <sys/sysctl.h>
47 #include <sys/unistd.h>
48 #include <sys/callout.h>
49 #include <sys/malloc.h>
50 #include <sys/priv.h>
51
52 #include <bus/u4b/usb.h>
53 #include <bus/u4b/usbdi.h>
54 #include <bus/u4b/usbdi_util.h>
55
56 #define USB_DEBUG_VAR usb_debug
57
58 #include <bus/u4b/usb_busdma.h>
59 #include <bus/u4b/usb_process.h>
60 #include <bus/u4b/usb_transfer.h>
61 #include <bus/u4b/usb_msctest.h>
62 #include <bus/u4b/usb_debug.h>
63 #include <bus/u4b/usb_device.h>
64 #include <bus/u4b/usb_request.h>
65 #include <bus/u4b/usb_util.h>
66 #include <bus/u4b/quirk/usb_quirk.h>
67
68 enum {
69         ST_COMMAND,
70         ST_DATA_RD,
71         ST_DATA_RD_CS,
72         ST_DATA_WR,
73         ST_DATA_WR_CS,
74         ST_STATUS,
75         ST_MAX,
76 };
77
78 enum {
79         DIR_IN,
80         DIR_OUT,
81         DIR_NONE,
82 };
83
84 #define SCSI_MAX_LEN    MAX(SCSI_FIXED_BLOCK_SIZE, USB_MSCTEST_BULK_SIZE)
85 #define SCSI_INQ_LEN    0x24
86 #define SCSI_SENSE_LEN  0xFF
87 #define SCSI_FIXED_BLOCK_SIZE 512       /* bytes */
88
89 static uint8_t scsi_test_unit_ready[] = { 0x00, 0x00, 0x00, 0x00, 0x00, 0x00 };
90 static uint8_t scsi_inquiry[] = { 0x12, 0x00, 0x00, 0x00, SCSI_INQ_LEN, 0x00 };
91 static uint8_t scsi_rezero_init[] =     { 0x01, 0x00, 0x00, 0x00, 0x00, 0x00 };
92 static uint8_t scsi_start_stop_unit[] = { 0x1b, 0x00, 0x00, 0x00, 0x02, 0x00 };
93 static uint8_t scsi_ztestor_eject[] =   { 0x85, 0x01, 0x01, 0x01, 0x18, 0x01,
94                                           0x01, 0x01, 0x01, 0x01, 0x00, 0x00 };
95 static uint8_t scsi_cmotech_eject[] =   { 0xff, 0x52, 0x44, 0x45, 0x56, 0x43,
96                                           0x48, 0x47 };
97 static uint8_t scsi_huawei_eject[] =    { 0x11, 0x06, 0x00, 0x00, 0x00, 0x00,
98                                           0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
99                                           0x00, 0x00, 0x00, 0x00 };
100 static uint8_t scsi_huawei_eject2[] =   { 0x11, 0x06, 0x20, 0x00, 0x00, 0x01,
101                                           0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
102                                           0x00, 0x00, 0x00, 0x00 };
103 static uint8_t scsi_tct_eject[] =       { 0x06, 0xf5, 0x04, 0x02, 0x52, 0x70 };
104 static uint8_t scsi_sync_cache[] =      { 0x35, 0x00, 0x00, 0x00, 0x00, 0x00,
105                                           0x00, 0x00, 0x00, 0x00 };
106 static uint8_t scsi_request_sense[] =   { 0x03, 0x00, 0x00, 0x00, 0x12, 0x00,
107                                           0x00, 0x00, 0x00, 0x00, 0x00, 0x00 };
108 static uint8_t scsi_read_capacity[] =   { 0x25, 0x00, 0x00, 0x00, 0x00, 0x00,
109                                           0x00, 0x00, 0x00, 0x00 };
110 static uint8_t scsi_prevent_removal[] = { 0x1e, 0, 0, 0, 1, 0 };
111 static uint8_t scsi_allow_removal[] =   { 0x1e, 0, 0, 0, 0, 0 };
112
113 #ifndef USB_MSCTEST_BULK_SIZE
114 #define USB_MSCTEST_BULK_SIZE   64      /* dummy */
115 #endif
116
117 #define ERR_CSW_FAILED          -1
118
119 /* Command Block Wrapper */
120 struct bbb_cbw {
121         uDWord  dCBWSignature;
122 #define CBWSIGNATURE    0x43425355
123         uDWord  dCBWTag;
124         uDWord  dCBWDataTransferLength;
125         uByte   bCBWFlags;
126 #define CBWFLAGS_OUT    0x00
127 #define CBWFLAGS_IN     0x80
128         uByte   bCBWLUN;
129         uByte   bCDBLength;
130 #define CBWCDBLENGTH    16
131         uByte   CBWCDB[CBWCDBLENGTH];
132 } __packed;
133
134 /* Command Status Wrapper */
135 struct bbb_csw {
136         uDWord  dCSWSignature;
137 #define CSWSIGNATURE    0x53425355
138         uDWord  dCSWTag;
139         uDWord  dCSWDataResidue;
140         uByte   bCSWStatus;
141 #define CSWSTATUS_GOOD  0x0
142 #define CSWSTATUS_FAILED        0x1
143 #define CSWSTATUS_PHASE 0x2
144 } __packed;
145
146 struct bbb_transfer {
147         struct lock lock;
148         struct cv cv;
149         struct bbb_cbw *cbw;
150         struct bbb_csw *csw;
151
152         struct usb_xfer *xfer[ST_MAX];
153
154         uint8_t *data_ptr;
155
156         usb_size_t data_len;            /* bytes */
157         usb_size_t data_rem;            /* bytes */
158         usb_timeout_t data_timeout;     /* ms */
159         usb_frlength_t actlen;          /* bytes */
160         usb_frlength_t buffer_size;     /* bytes */
161
162         uint8_t cmd_len;                /* bytes */
163         uint8_t dir;
164         uint8_t lun;
165         uint8_t state;
166         uint8_t status_try;
167         int     error;
168
169         uint8_t *buffer;
170 };
171
172 static usb_callback_t bbb_command_callback;
173 static usb_callback_t bbb_data_read_callback;
174 static usb_callback_t bbb_data_rd_cs_callback;
175 static usb_callback_t bbb_data_write_callback;
176 static usb_callback_t bbb_data_wr_cs_callback;
177 static usb_callback_t bbb_status_callback;
178 static usb_callback_t bbb_raw_write_callback;
179
180 static void     bbb_done(struct bbb_transfer *, int);
181 static void     bbb_transfer_start(struct bbb_transfer *, uint8_t);
182 static void     bbb_data_clear_stall_callback(struct usb_xfer *, uint8_t,
183                     uint8_t);
184 static int      bbb_command_start(struct bbb_transfer *, uint8_t, uint8_t,
185                     void *, size_t, void *, size_t, usb_timeout_t);
186 static struct bbb_transfer *bbb_attach(struct usb_device *, uint8_t, uint8_t);
187 static void     bbb_detach(struct bbb_transfer *);
188
189 static const struct usb_config bbb_config[ST_MAX] = {
190
191         [ST_COMMAND] = {
192                 .type = UE_BULK,
193                 .endpoint = UE_ADDR_ANY,
194                 .direction = UE_DIR_OUT,
195                 .bufsize = sizeof(struct bbb_cbw),
196                 .callback = &bbb_command_callback,
197                 .timeout = 4 * USB_MS_HZ,       /* 4 seconds */
198         },
199
200         [ST_DATA_RD] = {
201                 .type = UE_BULK,
202                 .endpoint = UE_ADDR_ANY,
203                 .direction = UE_DIR_IN,
204                 .bufsize = SCSI_MAX_LEN,
205                 .flags = {.proxy_buffer = 1,.short_xfer_ok = 1,},
206                 .callback = &bbb_data_read_callback,
207                 .timeout = 4 * USB_MS_HZ,       /* 4 seconds */
208         },
209
210         [ST_DATA_RD_CS] = {
211                 .type = UE_CONTROL,
212                 .endpoint = 0x00,       /* Control pipe */
213                 .direction = UE_DIR_ANY,
214                 .bufsize = sizeof(struct usb_device_request),
215                 .callback = &bbb_data_rd_cs_callback,
216                 .timeout = 1 * USB_MS_HZ,       /* 1 second  */
217         },
218
219         [ST_DATA_WR] = {
220                 .type = UE_BULK,
221                 .endpoint = UE_ADDR_ANY,
222                 .direction = UE_DIR_OUT,
223                 .bufsize = SCSI_MAX_LEN,
224                 .flags = {.ext_buffer = 1,.proxy_buffer = 1,},
225                 .callback = &bbb_data_write_callback,
226                 .timeout = 4 * USB_MS_HZ,       /* 4 seconds */
227         },
228
229         [ST_DATA_WR_CS] = {
230                 .type = UE_CONTROL,
231                 .endpoint = 0x00,       /* Control pipe */
232                 .direction = UE_DIR_ANY,
233                 .bufsize = sizeof(struct usb_device_request),
234                 .callback = &bbb_data_wr_cs_callback,
235                 .timeout = 1 * USB_MS_HZ,       /* 1 second  */
236         },
237
238         [ST_STATUS] = {
239                 .type = UE_BULK,
240                 .endpoint = UE_ADDR_ANY,
241                 .direction = UE_DIR_IN,
242                 .bufsize = sizeof(struct bbb_csw),
243                 .flags = {.short_xfer_ok = 1,},
244                 .callback = &bbb_status_callback,
245                 .timeout = 1 * USB_MS_HZ,       /* 1 second  */
246         },
247 };
248
249 static const struct usb_config bbb_raw_config[1] = {
250
251         [0] = {
252                 .type = UE_BULK_INTR,
253                 .endpoint = UE_ADDR_ANY,
254                 .direction = UE_DIR_OUT,
255                 .bufsize = SCSI_MAX_LEN,
256                 .flags = {.ext_buffer = 1,.proxy_buffer = 1,},
257                 .callback = &bbb_raw_write_callback,
258                 .timeout = 1 * USB_MS_HZ,       /* 1 second */
259         },
260 };
261
262 static void
263 bbb_done(struct bbb_transfer *sc, int error)
264 {
265         sc->error = error;
266         sc->state = ST_COMMAND;
267         sc->status_try = 1;
268         cv_signal(&sc->cv);
269 }
270
271 static void
272 bbb_transfer_start(struct bbb_transfer *sc, uint8_t xfer_index)
273 {
274         sc->state = xfer_index;
275         usbd_transfer_start(sc->xfer[xfer_index]);
276 }
277
278 static void
279 bbb_data_clear_stall_callback(struct usb_xfer *xfer,
280     uint8_t next_xfer, uint8_t stall_xfer)
281 {
282         struct bbb_transfer *sc = usbd_xfer_softc(xfer);
283
284         if (usbd_clear_stall_callback(xfer, sc->xfer[stall_xfer])) {
285                 switch (USB_GET_STATE(xfer)) {
286                 case USB_ST_SETUP:
287                 case USB_ST_TRANSFERRED:
288                         bbb_transfer_start(sc, next_xfer);
289                         break;
290                 default:
291                         bbb_done(sc, USB_ERR_STALLED);
292                         break;
293                 }
294         }
295 }
296
297 static void
298 bbb_command_callback(struct usb_xfer *xfer, usb_error_t error)
299 {
300         struct bbb_transfer *sc = usbd_xfer_softc(xfer);
301         uint32_t tag;
302
303         switch (USB_GET_STATE(xfer)) {
304         case USB_ST_TRANSFERRED:
305                 bbb_transfer_start
306                     (sc, ((sc->dir == DIR_IN) ? ST_DATA_RD :
307                     (sc->dir == DIR_OUT) ? ST_DATA_WR :
308                     ST_STATUS));
309                 break;
310
311         case USB_ST_SETUP:
312                 sc->status_try = 0;
313                 tag = UGETDW(sc->cbw->dCBWTag) + 1;
314                 USETDW(sc->cbw->dCBWSignature, CBWSIGNATURE);
315                 USETDW(sc->cbw->dCBWTag, tag);
316                 USETDW(sc->cbw->dCBWDataTransferLength, (uint32_t)sc->data_len);
317                 sc->cbw->bCBWFlags = ((sc->dir == DIR_IN) ? CBWFLAGS_IN : CBWFLAGS_OUT);
318                 sc->cbw->bCBWLUN = sc->lun;
319                 sc->cbw->bCDBLength = sc->cmd_len;
320                 if (sc->cbw->bCDBLength > sizeof(sc->cbw->CBWCDB)) {
321                         sc->cbw->bCDBLength = sizeof(sc->cbw->CBWCDB);
322                         DPRINTFN(0, "Truncating long command\n");
323                 }
324                 usbd_xfer_set_frame_len(xfer, 0,
325                     sizeof(struct bbb_cbw));
326                 usbd_transfer_submit(xfer);
327                 break;
328
329         default:                        /* Error */
330                 bbb_done(sc, error);
331                 break;
332         }
333 }
334
335 static void
336 bbb_data_read_callback(struct usb_xfer *xfer, usb_error_t error)
337 {
338         struct bbb_transfer *sc = usbd_xfer_softc(xfer);
339         usb_frlength_t max_bulk = usbd_xfer_max_len(xfer);
340         int actlen, sumlen;
341
342         usbd_xfer_status(xfer, &actlen, &sumlen, NULL, NULL);
343
344         switch (USB_GET_STATE(xfer)) {
345         case USB_ST_TRANSFERRED:
346                 sc->data_rem -= actlen;
347                 sc->data_ptr += actlen;
348                 sc->actlen += actlen;
349
350                 if (actlen < sumlen) {
351                         /* short transfer */
352                         sc->data_rem = 0;
353                 }
354         case USB_ST_SETUP:
355                 DPRINTF("max_bulk=%d, data_rem=%d\n",
356                     max_bulk, sc->data_rem);
357
358                 if (sc->data_rem == 0) {
359                         bbb_transfer_start(sc, ST_STATUS);
360                         break;
361                 }
362                 if (max_bulk > sc->data_rem) {
363                         max_bulk = sc->data_rem;
364                 }
365                 usbd_xfer_set_timeout(xfer, sc->data_timeout);
366                 usbd_xfer_set_frame_data(xfer, 0, sc->data_ptr, max_bulk);
367                 usbd_transfer_submit(xfer);
368                 break;
369
370         default:                        /* Error */
371                 if (error == USB_ERR_CANCELLED) {
372                         bbb_done(sc, error);
373                 } else {
374                         bbb_transfer_start(sc, ST_DATA_RD_CS);
375                 }
376                 break;
377         }
378 }
379
380 static void
381 bbb_data_rd_cs_callback(struct usb_xfer *xfer, usb_error_t error)
382 {
383         bbb_data_clear_stall_callback(xfer, ST_STATUS,
384             ST_DATA_RD);
385 }
386
387 static void
388 bbb_data_write_callback(struct usb_xfer *xfer, usb_error_t error)
389 {
390         struct bbb_transfer *sc = usbd_xfer_softc(xfer);
391         usb_frlength_t max_bulk = usbd_xfer_max_len(xfer);
392         int actlen, sumlen;
393
394         usbd_xfer_status(xfer, &actlen, &sumlen, NULL, NULL);
395
396         switch (USB_GET_STATE(xfer)) {
397         case USB_ST_TRANSFERRED:
398                 sc->data_rem -= actlen;
399                 sc->data_ptr += actlen;
400                 sc->actlen += actlen;
401
402                 if (actlen < sumlen) {
403                         /* short transfer */
404                         sc->data_rem = 0;
405                 }
406         case USB_ST_SETUP:
407                 DPRINTF("max_bulk=%d, data_rem=%d\n",
408                     max_bulk, sc->data_rem);
409
410                 if (sc->data_rem == 0) {
411                         bbb_transfer_start(sc, ST_STATUS);
412                         break;
413                 }
414                 if (max_bulk > sc->data_rem) {
415                         max_bulk = sc->data_rem;
416                 }
417                 usbd_xfer_set_timeout(xfer, sc->data_timeout);
418                 usbd_xfer_set_frame_data(xfer, 0, sc->data_ptr, max_bulk);
419                 usbd_transfer_submit(xfer);
420                 break;
421
422         default:                        /* Error */
423                 if (error == USB_ERR_CANCELLED) {
424                         bbb_done(sc, error);
425                 } else {
426                         bbb_transfer_start(sc, ST_DATA_WR_CS);
427                 }
428                 break;
429         }
430 }
431
432 static void
433 bbb_data_wr_cs_callback(struct usb_xfer *xfer, usb_error_t error)
434 {
435         bbb_data_clear_stall_callback(xfer, ST_STATUS,
436             ST_DATA_WR);
437 }
438
439 static void
440 bbb_status_callback(struct usb_xfer *xfer, usb_error_t error)
441 {
442         struct bbb_transfer *sc = usbd_xfer_softc(xfer);
443         int actlen;
444         int sumlen;
445
446         usbd_xfer_status(xfer, &actlen, &sumlen, NULL, NULL);
447
448         switch (USB_GET_STATE(xfer)) {
449         case USB_ST_TRANSFERRED:
450
451                 /* very simple status check */
452
453                 if (actlen < (int)sizeof(struct bbb_csw)) {
454                         bbb_done(sc, USB_ERR_SHORT_XFER);
455                 } else if (sc->csw->bCSWStatus == CSWSTATUS_GOOD) {
456                         bbb_done(sc, 0);        /* success */
457                 } else {
458                         bbb_done(sc, ERR_CSW_FAILED);   /* error */
459                 }
460                 break;
461
462         case USB_ST_SETUP:
463                 usbd_xfer_set_frame_len(xfer, 0,
464                     sizeof(struct bbb_csw));
465                 usbd_transfer_submit(xfer);
466                 break;
467
468         default:
469                 DPRINTF("Failed to read CSW: %s, try %d\n",
470                     usbd_errstr(error), sc->status_try);
471
472                 if (error == USB_ERR_CANCELLED || sc->status_try) {
473                         bbb_done(sc, error);
474                 } else {
475                         sc->status_try = 1;
476                         bbb_transfer_start(sc, ST_DATA_RD_CS);
477                 }
478                 break;
479         }
480 }
481
482 static void
483 bbb_raw_write_callback(struct usb_xfer *xfer, usb_error_t error)
484 {
485         struct bbb_transfer *sc = usbd_xfer_softc(xfer);
486         usb_frlength_t max_bulk = usbd_xfer_max_len(xfer);
487         int actlen, sumlen;
488
489         usbd_xfer_status(xfer, &actlen, &sumlen, NULL, NULL);
490
491         switch (USB_GET_STATE(xfer)) {
492         case USB_ST_TRANSFERRED:
493                 sc->data_rem -= actlen;
494                 sc->data_ptr += actlen;
495                 sc->actlen += actlen;
496
497                 if (actlen < sumlen) {
498                         /* short transfer */
499                         sc->data_rem = 0;
500                 }
501         case USB_ST_SETUP:
502                 DPRINTF("max_bulk=%d, data_rem=%d\n",
503                     max_bulk, sc->data_rem);
504
505                 if (sc->data_rem == 0) {
506                         bbb_done(sc, 0);
507                         break;
508                 }
509                 if (max_bulk > sc->data_rem) {
510                         max_bulk = sc->data_rem;
511                 }
512                 usbd_xfer_set_timeout(xfer, sc->data_timeout);
513                 usbd_xfer_set_frame_data(xfer, 0, sc->data_ptr, max_bulk);
514                 usbd_transfer_submit(xfer);
515                 break;
516
517         default:                        /* Error */
518                 bbb_done(sc, error);
519                 break;
520         }
521 }
522
523 /*------------------------------------------------------------------------*
524  *      bbb_command_start - execute a SCSI command synchronously
525  *
526  * Return values
527  * 0: Success
528  * Else: Failure
529  *------------------------------------------------------------------------*/
530 static int
531 bbb_command_start(struct bbb_transfer *sc, uint8_t dir, uint8_t lun,
532     void *data_ptr, size_t data_len, void *cmd_ptr, size_t cmd_len,
533     usb_timeout_t data_timeout)
534 {
535         sc->lun = lun;
536         sc->dir = data_len ? dir : DIR_NONE;
537         sc->data_ptr = data_ptr;
538         sc->data_len = data_len;
539         sc->data_rem = data_len;
540         sc->data_timeout = (data_timeout + USB_MS_HZ);
541         sc->actlen = 0;
542         sc->error = 0;
543         sc->cmd_len = cmd_len;
544         memset(&sc->cbw->CBWCDB, 0, sizeof(sc->cbw->CBWCDB));
545         memcpy(&sc->cbw->CBWCDB, cmd_ptr, cmd_len);
546         DPRINTFN(1, "SCSI cmd_len = %d, cmd %s\n", (int)cmd_len, (char *)sc->cbw->CBWCDB);
547
548         lockmgr(&sc->lock, LK_EXCLUSIVE);
549         usbd_transfer_start(sc->xfer[sc->state]);
550
551         while (usbd_transfer_pending(sc->xfer[sc->state])) {
552                 cv_wait(&sc->cv, &sc->lock);
553         }
554         lockmgr(&sc->lock, LK_RELEASE);
555         return (sc->error);
556 }
557
558 /*------------------------------------------------------------------------*
559  *      bbb_raw_write - write a raw BULK message synchronously
560  *
561  * Return values
562  * 0: Success
563  * Else: Failure
564  *------------------------------------------------------------------------*/
565 static int
566 bbb_raw_write(struct bbb_transfer *sc, const void *data_ptr, size_t data_len,
567     usb_timeout_t data_timeout)
568 {
569         sc->data_ptr = __DECONST(void *, data_ptr);
570         sc->data_len = data_len;
571         sc->data_rem = data_len;
572         sc->data_timeout = (data_timeout + USB_MS_HZ);
573         sc->actlen = 0;
574         sc->error = 0;
575
576 //      DPRINTFN(1, "BULK DATA = %*D\n", (int)data_len,
577 //          (const char *)data_ptr, ":");
578
579         lockmgr(&sc->lock, LK_EXCLUSIVE);
580         usbd_transfer_start(sc->xfer[0]);
581         while (usbd_transfer_pending(sc->xfer[0]))
582                 cv_wait(&sc->cv, &sc->lock);
583         lockmgr(&sc->lock, LK_RELEASE);
584         return (sc->error);
585 }
586
587 static struct bbb_transfer *
588 bbb_attach(struct usb_device *udev, uint8_t iface_index,
589     uint8_t bInterfaceClass)
590 {
591         struct usb_interface *iface;
592         struct usb_interface_descriptor *id;
593         const struct usb_config *pconfig;
594         struct bbb_transfer *sc;
595         usb_error_t err;
596         int nconfig;
597
598 #if USB_HAVE_MSCTEST_DETACH
599         uint8_t do_unlock;
600
601         /* Prevent re-enumeration */
602         do_unlock = usbd_enum_lock(udev);
603
604         /*
605          * Make sure any driver which is hooked up to this interface,
606          * like umass is gone:
607          */
608         usb_detach_device(udev, iface_index, 0);
609
610         if (do_unlock)
611                 usbd_enum_unlock(udev);
612 #endif
613
614         iface = usbd_get_iface(udev, iface_index);
615         if (iface == NULL)
616                 return (NULL);
617
618         id = iface->idesc;
619         if (id == NULL || id->bInterfaceClass != bInterfaceClass)
620                 return (NULL);
621
622         switch (id->bInterfaceClass) {
623         case UICLASS_MASS:
624                 switch (id->bInterfaceSubClass) {
625                 case UISUBCLASS_SCSI:
626                 case UISUBCLASS_UFI:
627                 case UISUBCLASS_SFF8020I:
628                 case UISUBCLASS_SFF8070I:
629                         break;
630                 default:
631                         return (NULL);
632                 }
633                 switch (id->bInterfaceProtocol) {
634                 case UIPROTO_MASS_BBB_OLD:
635                 case UIPROTO_MASS_BBB:
636                         break;
637                 default:
638                         return (NULL);
639                 }
640                 pconfig = bbb_config;
641                 nconfig = ST_MAX;
642                 break;
643         case UICLASS_HID:
644                 switch (id->bInterfaceSubClass) {
645                 case 0:
646                         break;
647                 default:
648                         return (NULL);
649                 }
650                 pconfig = bbb_raw_config;
651                 nconfig = 1;
652                 break;
653         default:
654                 return (NULL);
655         }
656
657         sc = kmalloc(sizeof(*sc), M_USB, M_WAITOK | M_ZERO);
658         lockinit(&sc->lock, "USB autoinstall", 0, 0);
659         cv_init(&sc->cv, "WBBB");
660
661         err = usbd_transfer_setup(udev, &iface_index, sc->xfer, pconfig,
662             nconfig, sc, &sc->lock);
663         if (err) {
664                 bbb_detach(sc);
665                 return (NULL);
666         }
667         switch (id->bInterfaceClass) {
668         case UICLASS_MASS:
669                 /* store pointer to DMA buffers */
670                 sc->buffer = usbd_xfer_get_frame_buffer(
671                     sc->xfer[ST_DATA_RD], 0);
672                 sc->buffer_size =
673                     usbd_xfer_max_len(sc->xfer[ST_DATA_RD]);
674                 sc->cbw = usbd_xfer_get_frame_buffer(
675                     sc->xfer[ST_COMMAND], 0);
676                 sc->csw = usbd_xfer_get_frame_buffer(
677                     sc->xfer[ST_STATUS], 0);
678                 break;
679         default:
680                 break;
681         }
682         return (sc);
683 }
684
685 static void
686 bbb_detach(struct bbb_transfer *sc)
687 {
688         usbd_transfer_unsetup(sc->xfer, ST_MAX);
689         lockuninit(&sc->lock);
690         cv_destroy(&sc->cv);
691         kfree(sc, M_USB);
692 }
693
694 /*------------------------------------------------------------------------*
695  *      usb_iface_is_cdrom
696  *
697  * Return values:
698  * 1: This interface is an auto install disk (CD-ROM)
699  * 0: Not an auto install disk.
700  *------------------------------------------------------------------------*/
701 int
702 usb_iface_is_cdrom(struct usb_device *udev, uint8_t iface_index)
703 {
704         struct bbb_transfer *sc;
705         uint8_t timeout;
706         uint8_t is_cdrom;
707         uint8_t sid_type;
708         int err;
709
710         sc = bbb_attach(udev, iface_index, UICLASS_MASS);
711         if (sc == NULL)
712                 return (0);
713
714         is_cdrom = 0;
715         timeout = 4;    /* tries */
716         while (--timeout) {
717                 err = bbb_command_start(sc, DIR_IN, 0, sc->buffer,
718                     SCSI_INQ_LEN, &scsi_inquiry, sizeof(scsi_inquiry),
719                     USB_MS_HZ);
720
721                 if (err == 0 && sc->actlen > 0) {
722                         sid_type = sc->buffer[0] & 0x1F;
723                         if (sid_type == 0x05)
724                                 is_cdrom = 1;
725                         break;
726                 } else if (err != ERR_CSW_FAILED)
727                         break;  /* non retryable error */
728                 usb_pause_mtx(NULL, hz);
729         }
730         bbb_detach(sc);
731         return (is_cdrom);
732 }
733
734 static uint8_t
735 usb_msc_get_max_lun(struct usb_device *udev, uint8_t iface_index)
736 {
737         struct usb_device_request req;
738         usb_error_t err;
739         uint8_t buf = 0;
740
741
742         /* The Get Max Lun command is a class-specific request. */
743         req.bmRequestType = UT_READ_CLASS_INTERFACE;
744         req.bRequest = 0xFE;            /* GET_MAX_LUN */
745         USETW(req.wValue, 0);
746         req.wIndex[0] = iface_index;
747         req.wIndex[1] = 0;
748         USETW(req.wLength, 1);
749
750         err = usbd_do_request(udev, NULL, &req, &buf);
751         if (err)
752                 buf = 0;
753
754         return (buf);
755 }
756
757 usb_error_t
758 usb_msc_auto_quirk(struct usb_device *udev, uint8_t iface_index)
759 {
760         struct bbb_transfer *sc;
761         uint8_t timeout;
762         uint8_t is_no_direct;
763         uint8_t sid_type;
764         int err;
765
766         sc = bbb_attach(udev, iface_index, UICLASS_MASS);
767         if (sc == NULL)
768                 return (0);
769
770         /*
771          * Some devices need a delay after that the configuration
772          * value is set to function properly:
773          */
774         usb_pause_mtx(NULL, hz);
775
776         if (usb_msc_get_max_lun(udev, iface_index) == 0) {
777                 DPRINTF("Device has only got one LUN.\n");
778                 usbd_add_dynamic_quirk(udev, UQ_MSC_NO_GETMAXLUN);
779         }
780
781         is_no_direct = 1;
782         for (timeout = 4; timeout != 0; timeout--) {
783                 err = bbb_command_start(sc, DIR_IN, 0, sc->buffer,
784                     SCSI_INQ_LEN, &scsi_inquiry, sizeof(scsi_inquiry),
785                     USB_MS_HZ);
786
787                 if (err == 0 && sc->actlen > 0) {
788                         sid_type = sc->buffer[0] & 0x1F;
789                         if (sid_type == 0x00)
790                                 is_no_direct = 0;
791                         break;
792                 } else if (err != ERR_CSW_FAILED) {
793                         DPRINTF("Device is not responding "
794                             "properly to SCSI INQUIRY command.\n");
795                         goto error;     /* non retryable error */
796                 }
797                 usb_pause_mtx(NULL, hz);
798         }
799
800         if (is_no_direct) {
801                 DPRINTF("Device is not direct access.\n");
802                 goto done;
803         }
804
805         err = bbb_command_start(sc, DIR_IN, 0, NULL, 0,
806             &scsi_test_unit_ready, sizeof(scsi_test_unit_ready),
807             USB_MS_HZ);
808
809         if (err != 0) {
810                 if (err != ERR_CSW_FAILED)
811                         goto error;
812                 DPRINTF("Test unit ready failed\n");
813         }
814
815         err = bbb_command_start(sc, DIR_OUT, 0, NULL, 0,
816             &scsi_prevent_removal, sizeof(scsi_prevent_removal),
817             USB_MS_HZ);
818
819         if (err == 0) {
820                 err = bbb_command_start(sc, DIR_OUT, 0, NULL, 0,
821                     &scsi_allow_removal, sizeof(scsi_allow_removal),
822                     USB_MS_HZ);
823         }
824
825         if (err != 0) {
826                 if (err != ERR_CSW_FAILED)
827                         goto error;
828                 DPRINTF("Device doesn't handle prevent and allow removal\n");
829                 usbd_add_dynamic_quirk(udev, UQ_MSC_NO_PREVENT_ALLOW);
830         }
831
832         timeout = 1;
833
834 retry_sync_cache:
835         err = bbb_command_start(sc, DIR_IN, 0, NULL, 0,
836             &scsi_sync_cache, sizeof(scsi_sync_cache),
837             USB_MS_HZ);
838
839         if (err != 0) {
840
841                 if (err != ERR_CSW_FAILED)
842                         goto error;
843
844                 DPRINTF("Device doesn't handle synchronize cache\n");
845
846                 usbd_add_dynamic_quirk(udev, UQ_MSC_NO_SYNC_CACHE);
847         } else {
848
849                 /*
850                  * Certain Kingston memory sticks fail the first
851                  * read capacity after a synchronize cache command
852                  * has been issued. Disable the synchronize cache
853                  * command for such devices.
854                  */
855
856                 err = bbb_command_start(sc, DIR_IN, 0, sc->buffer, 8,
857                     &scsi_read_capacity, sizeof(scsi_read_capacity),
858                     USB_MS_HZ);
859
860                 if (err != 0) {
861                         if (err != ERR_CSW_FAILED)
862                                 goto error;
863
864                         err = bbb_command_start(sc, DIR_IN, 0, sc->buffer, 8,
865                             &scsi_read_capacity, sizeof(scsi_read_capacity),
866                             USB_MS_HZ);
867
868                         if (err == 0) {
869                                 if (timeout--)
870                                         goto retry_sync_cache;
871
872                                 DPRINTF("Device most likely doesn't "
873                                     "handle synchronize cache\n");
874
875                                 usbd_add_dynamic_quirk(udev,
876                                     UQ_MSC_NO_SYNC_CACHE);
877                         } else {
878                                 if (err != ERR_CSW_FAILED)
879                                         goto error;
880                         }
881                 }
882         }
883
884         /* clear sense status of any failed commands on the device */
885
886         err = bbb_command_start(sc, DIR_IN, 0, sc->buffer,
887             SCSI_INQ_LEN, &scsi_inquiry, sizeof(scsi_inquiry),
888             USB_MS_HZ);
889
890         DPRINTF("Inquiry = %d\n", err);
891
892         if (err != 0) {
893
894                 if (err != ERR_CSW_FAILED)
895                         goto error;
896         }
897
898         err = bbb_command_start(sc, DIR_IN, 0, sc->buffer,
899             SCSI_SENSE_LEN, &scsi_request_sense,
900             sizeof(scsi_request_sense), USB_MS_HZ);
901
902         DPRINTF("Request sense = %d\n", err);
903
904         if (err != 0) {
905
906                 if (err != ERR_CSW_FAILED)
907                         goto error;
908         }
909
910 done:
911         bbb_detach(sc);
912         return (0);
913
914 error:
915         bbb_detach(sc);
916
917         DPRINTF("Device did not respond, enabling all quirks\n");
918
919         usbd_add_dynamic_quirk(udev, UQ_MSC_NO_SYNC_CACHE);
920         usbd_add_dynamic_quirk(udev, UQ_MSC_NO_PREVENT_ALLOW);
921         usbd_add_dynamic_quirk(udev, UQ_MSC_NO_TEST_UNIT_READY);
922
923         /* Need to re-enumerate the device */
924         usbd_req_re_enumerate(udev, NULL);
925
926         return (USB_ERR_STALLED);
927 }
928
929 usb_error_t
930 usb_msc_eject(struct usb_device *udev, uint8_t iface_index, int method)
931 {
932         struct bbb_transfer *sc;
933         usb_error_t err;
934
935         sc = bbb_attach(udev, iface_index, UICLASS_MASS);
936         if (sc == NULL)
937                 return (USB_ERR_INVAL);
938
939         switch (method) {
940         case MSC_EJECT_STOPUNIT:
941                 err = bbb_command_start(sc, DIR_IN, 0, NULL, 0,
942                     &scsi_test_unit_ready, sizeof(scsi_test_unit_ready),
943                     USB_MS_HZ);
944                 DPRINTF("Test unit ready status: %s\n", usbd_errstr(err));
945                 err = bbb_command_start(sc, DIR_IN, 0, NULL, 0,
946                     &scsi_start_stop_unit, sizeof(scsi_start_stop_unit),
947                     USB_MS_HZ);
948                 break;
949         case MSC_EJECT_REZERO:
950                 err = bbb_command_start(sc, DIR_IN, 0, NULL, 0,
951                     &scsi_rezero_init, sizeof(scsi_rezero_init),
952                     USB_MS_HZ);
953                 break;
954         case MSC_EJECT_ZTESTOR:
955                 err = bbb_command_start(sc, DIR_IN, 0, NULL, 0,
956                     &scsi_ztestor_eject, sizeof(scsi_ztestor_eject),
957                     USB_MS_HZ);
958                 break;
959         case MSC_EJECT_CMOTECH:
960                 err = bbb_command_start(sc, DIR_IN, 0, NULL, 0,
961                     &scsi_cmotech_eject, sizeof(scsi_cmotech_eject),
962                     USB_MS_HZ);
963                 break;
964         case MSC_EJECT_HUAWEI:
965                 err = bbb_command_start(sc, DIR_IN, 0, NULL, 0,
966                     &scsi_huawei_eject, sizeof(scsi_huawei_eject),
967                     USB_MS_HZ);
968                 break;
969         case MSC_EJECT_HUAWEI2:
970                 err = bbb_command_start(sc, DIR_IN, 0, NULL, 0,
971                     &scsi_huawei_eject2, sizeof(scsi_huawei_eject2),
972                     USB_MS_HZ);
973                 break;
974         case MSC_EJECT_TCT:
975                 /*
976                  * TCTMobile needs DIR_IN flag. To get it, we
977                  * supply a dummy data with the command.
978                  */
979                 err = bbb_command_start(sc, DIR_IN, 0, sc->buffer,
980                     sc->buffer_size, &scsi_tct_eject,
981                     sizeof(scsi_tct_eject), USB_MS_HZ);
982                 break;
983         default:
984                 DPRINTF("Unknown eject method (%d)\n", method);
985                 bbb_detach(sc);
986                 return (USB_ERR_INVAL);
987         }
988
989         DPRINTF("Eject CD command status: %s\n", usbd_errstr(err));
990
991         bbb_detach(sc);
992         return (0);
993 }
994
995 usb_error_t
996 usb_dymo_eject(struct usb_device *udev, uint8_t iface_index)
997 {
998         static const uint8_t data[3] = { 0x1b, 0x5a, 0x01 };
999         struct bbb_transfer *sc;
1000         usb_error_t err;
1001
1002         sc = bbb_attach(udev, iface_index, UICLASS_HID);
1003         if (sc == NULL)
1004                 return (USB_ERR_INVAL);
1005         err = bbb_raw_write(sc, data, sizeof(data), USB_MS_HZ);
1006         bbb_detach(sc);
1007         return (err);
1008 }
1009
1010 usb_error_t
1011 usb_msc_read_10(struct usb_device *udev, uint8_t iface_index,
1012     uint32_t lba, uint32_t blocks, void *buffer)
1013 {
1014         struct bbb_transfer *sc;
1015         uint8_t cmd[10];
1016         usb_error_t err;
1017
1018         cmd[0] = 0x28;          /* READ_10 */
1019         cmd[1] = 0;
1020         cmd[2] = lba >> 24;
1021         cmd[3] = lba >> 16;
1022         cmd[4] = lba >> 8;
1023         cmd[5] = lba >> 0;
1024         cmd[6] = 0;
1025         cmd[7] = blocks >> 8;
1026         cmd[8] = blocks;
1027         cmd[9] = 0;
1028
1029         sc = bbb_attach(udev, iface_index, UICLASS_MASS);
1030         if (sc == NULL)
1031                 return (USB_ERR_INVAL);
1032
1033         err = bbb_command_start(sc, DIR_IN, 0, buffer,
1034             blocks * SCSI_FIXED_BLOCK_SIZE, cmd, 10, USB_MS_HZ);
1035
1036         bbb_detach(sc);
1037
1038         return (err);
1039 }
1040
1041 usb_error_t
1042 usb_msc_write_10(struct usb_device *udev, uint8_t iface_index,
1043     uint32_t lba, uint32_t blocks, void *buffer)
1044 {
1045         struct bbb_transfer *sc;
1046         uint8_t cmd[10];
1047         usb_error_t err;
1048
1049         cmd[0] = 0x2a;          /* WRITE_10 */
1050         cmd[1] = 0;
1051         cmd[2] = lba >> 24;
1052         cmd[3] = lba >> 16;
1053         cmd[4] = lba >> 8;
1054         cmd[5] = lba >> 0;
1055         cmd[6] = 0;
1056         cmd[7] = blocks >> 8;
1057         cmd[8] = blocks;
1058         cmd[9] = 0;
1059
1060         sc = bbb_attach(udev, iface_index, UICLASS_MASS);
1061         if (sc == NULL)
1062                 return (USB_ERR_INVAL);
1063
1064         err = bbb_command_start(sc, DIR_OUT, 0, buffer,
1065             blocks * SCSI_FIXED_BLOCK_SIZE, cmd, 10, USB_MS_HZ);
1066
1067         bbb_detach(sc);
1068
1069         return (err);
1070 }
1071
1072 usb_error_t
1073 usb_msc_read_capacity(struct usb_device *udev, uint8_t iface_index,
1074     uint32_t *lba_last, uint32_t *block_size)
1075 {
1076         struct bbb_transfer *sc;
1077         usb_error_t err;
1078
1079         sc = bbb_attach(udev, iface_index, UICLASS_MASS);
1080         if (sc == NULL)
1081                 return (USB_ERR_INVAL);
1082
1083         err = bbb_command_start(sc, DIR_IN, 0, sc->buffer, 8,
1084             &scsi_read_capacity, sizeof(scsi_read_capacity),
1085             USB_MS_HZ);
1086
1087         *lba_last =
1088             (sc->buffer[0] << 24) | 
1089             (sc->buffer[1] << 16) |
1090             (sc->buffer[2] << 8) |
1091             (sc->buffer[3]);
1092
1093         *block_size =
1094             (sc->buffer[4] << 24) | 
1095             (sc->buffer[5] << 16) |
1096             (sc->buffer[6] << 8) |
1097             (sc->buffer[7]);
1098
1099         /* we currently only support one block size */
1100         if (*block_size != SCSI_FIXED_BLOCK_SIZE)
1101                 err = USB_ERR_INVAL;
1102
1103         bbb_detach(sc);
1104
1105         return (err);
1106 }