]> CyberLeo.Net >> Repos - FreeBSD/stable/10.git/blob - sys/dev/usb/usb_msctest.c
MFC r282469:
[FreeBSD/stable/10.git] / sys / dev / usb / usb_msctest.c
1 /* $FreeBSD$ */
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 #ifdef USB_GLOBAL_INCLUDE_FILE
36 #include USB_GLOBAL_INCLUDE_FILE
37 #else
38 #include <sys/stdint.h>
39 #include <sys/stddef.h>
40 #include <sys/param.h>
41 #include <sys/queue.h>
42 #include <sys/types.h>
43 #include <sys/systm.h>
44 #include <sys/kernel.h>
45 #include <sys/bus.h>
46 #include <sys/module.h>
47 #include <sys/lock.h>
48 #include <sys/mutex.h>
49 #include <sys/condvar.h>
50 #include <sys/sysctl.h>
51 #include <sys/sx.h>
52 #include <sys/unistd.h>
53 #include <sys/callout.h>
54 #include <sys/malloc.h>
55 #include <sys/priv.h>
56
57 #include <dev/usb/usb.h>
58 #include <dev/usb/usbdi.h>
59 #include <dev/usb/usbdi_util.h>
60
61 #define USB_DEBUG_VAR usb_debug
62
63 #include <dev/usb/usb_busdma.h>
64 #include <dev/usb/usb_process.h>
65 #include <dev/usb/usb_transfer.h>
66 #include <dev/usb/usb_msctest.h>
67 #include <dev/usb/usb_debug.h>
68 #include <dev/usb/usb_device.h>
69 #include <dev/usb/usb_request.h>
70 #include <dev/usb/usb_util.h>
71 #include <dev/usb/quirk/usb_quirk.h>
72 #endif                  /* USB_GLOBAL_INCLUDE_FILE */
73
74 enum {
75         ST_COMMAND,
76         ST_DATA_RD,
77         ST_DATA_RD_CS,
78         ST_DATA_WR,
79         ST_DATA_WR_CS,
80         ST_STATUS,
81         ST_MAX,
82 };
83
84 enum {
85         DIR_IN,
86         DIR_OUT,
87         DIR_NONE,
88 };
89
90 #define SCSI_MAX_LEN    MAX(0x100, BULK_SIZE)
91 #define SCSI_INQ_LEN    0x24
92 #define SCSI_SENSE_LEN  0xFF
93
94 static uint8_t scsi_test_unit_ready[] = { 0x00, 0x00, 0x00, 0x00, 0x00, 0x00 };
95 static uint8_t scsi_inquiry[] = { 0x12, 0x00, 0x00, 0x00, SCSI_INQ_LEN, 0x00 };
96 static uint8_t scsi_rezero_init[] =     { 0x01, 0x00, 0x00, 0x00, 0x00, 0x00 };
97 static uint8_t scsi_start_stop_unit[] = { 0x1b, 0x00, 0x00, 0x00, 0x02, 0x00 };
98 static uint8_t scsi_ztestor_eject[] =   { 0x85, 0x01, 0x01, 0x01, 0x18, 0x01,
99                                           0x01, 0x01, 0x01, 0x01, 0x00, 0x00 };
100 static uint8_t scsi_cmotech_eject[] =   { 0xff, 0x52, 0x44, 0x45, 0x56, 0x43,
101                                           0x48, 0x47 };
102 static uint8_t scsi_huawei_eject[] =    { 0x11, 0x06, 0x00, 0x00, 0x00, 0x00,
103                                           0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
104                                           0x00, 0x00, 0x00, 0x00 };
105 static uint8_t scsi_huawei_eject2[] =   { 0x11, 0x06, 0x20, 0x00, 0x00, 0x01,
106                                           0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
107                                           0x00, 0x00, 0x00, 0x00 };
108 static uint8_t scsi_tct_eject[] =       { 0x06, 0xf5, 0x04, 0x02, 0x52, 0x70 };
109 static uint8_t scsi_sync_cache[] =      { 0x35, 0x00, 0x00, 0x00, 0x00, 0x00,
110                                           0x00, 0x00, 0x00, 0x00 };
111 static uint8_t scsi_request_sense[] =   { 0x03, 0x00, 0x00, 0x00, 0x12, 0x00,
112                                           0x00, 0x00, 0x00, 0x00, 0x00, 0x00 };
113 static uint8_t scsi_read_capacity[] =   { 0x25, 0x00, 0x00, 0x00, 0x00, 0x00,
114                                           0x00, 0x00, 0x00, 0x00 };
115 static uint8_t scsi_prevent_removal[] = { 0x1e, 0, 0, 0, 1, 0 };
116 static uint8_t scsi_allow_removal[] =   { 0x1e, 0, 0, 0, 0, 0 };
117
118 #define BULK_SIZE               64      /* dummy */
119 #define ERR_CSW_FAILED          -1
120
121 /* Command Block Wrapper */
122 struct bbb_cbw {
123         uDWord  dCBWSignature;
124 #define CBWSIGNATURE    0x43425355
125         uDWord  dCBWTag;
126         uDWord  dCBWDataTransferLength;
127         uByte   bCBWFlags;
128 #define CBWFLAGS_OUT    0x00
129 #define CBWFLAGS_IN     0x80
130         uByte   bCBWLUN;
131         uByte   bCDBLength;
132 #define CBWCDBLENGTH    16
133         uByte   CBWCDB[CBWCDBLENGTH];
134 } __packed;
135
136 /* Command Status Wrapper */
137 struct bbb_csw {
138         uDWord  dCSWSignature;
139 #define CSWSIGNATURE    0x53425355
140         uDWord  dCSWTag;
141         uDWord  dCSWDataResidue;
142         uByte   bCSWStatus;
143 #define CSWSTATUS_GOOD  0x0
144 #define CSWSTATUS_FAILED        0x1
145 #define CSWSTATUS_PHASE 0x2
146 } __packed;
147
148 struct bbb_transfer {
149         struct mtx mtx;
150         struct cv cv;
151         struct bbb_cbw *cbw;
152         struct bbb_csw *csw;
153
154         struct usb_xfer *xfer[ST_MAX];
155
156         uint8_t *data_ptr;
157
158         usb_size_t data_len;            /* bytes */
159         usb_size_t data_rem;            /* bytes */
160         usb_timeout_t data_timeout;     /* ms */
161         usb_frlength_t actlen;          /* bytes */
162         usb_frlength_t buffer_size;     /* bytes */
163
164         uint8_t cmd_len;                /* bytes */
165         uint8_t dir;
166         uint8_t lun;
167         uint8_t state;
168         uint8_t status_try;
169         int     error;
170
171         uint8_t *buffer;
172 };
173
174 static usb_callback_t bbb_command_callback;
175 static usb_callback_t bbb_data_read_callback;
176 static usb_callback_t bbb_data_rd_cs_callback;
177 static usb_callback_t bbb_data_write_callback;
178 static usb_callback_t bbb_data_wr_cs_callback;
179 static usb_callback_t bbb_status_callback;
180
181 static void     bbb_done(struct bbb_transfer *, int);
182 static void     bbb_transfer_start(struct bbb_transfer *, uint8_t);
183 static void     bbb_data_clear_stall_callback(struct usb_xfer *, uint8_t,
184                     uint8_t);
185 static int      bbb_command_start(struct bbb_transfer *, uint8_t, uint8_t,
186                     void *, size_t, void *, size_t, usb_timeout_t);
187 static struct bbb_transfer *bbb_attach(struct usb_device *, uint8_t);
188 static void     bbb_detach(struct bbb_transfer *);
189
190 static const struct usb_config bbb_config[ST_MAX] = {
191
192         [ST_COMMAND] = {
193                 .type = UE_BULK,
194                 .endpoint = UE_ADDR_ANY,
195                 .direction = UE_DIR_OUT,
196                 .bufsize = sizeof(struct bbb_cbw),
197                 .callback = &bbb_command_callback,
198                 .timeout = 4 * USB_MS_HZ,       /* 4 seconds */
199         },
200
201         [ST_DATA_RD] = {
202                 .type = UE_BULK,
203                 .endpoint = UE_ADDR_ANY,
204                 .direction = UE_DIR_IN,
205                 .bufsize = SCSI_MAX_LEN,
206                 .flags = {.proxy_buffer = 1,.short_xfer_ok = 1,},
207                 .callback = &bbb_data_read_callback,
208                 .timeout = 4 * USB_MS_HZ,       /* 4 seconds */
209         },
210
211         [ST_DATA_RD_CS] = {
212                 .type = UE_CONTROL,
213                 .endpoint = 0x00,       /* Control pipe */
214                 .direction = UE_DIR_ANY,
215                 .bufsize = sizeof(struct usb_device_request),
216                 .callback = &bbb_data_rd_cs_callback,
217                 .timeout = 1 * USB_MS_HZ,       /* 1 second  */
218         },
219
220         [ST_DATA_WR] = {
221                 .type = UE_BULK,
222                 .endpoint = UE_ADDR_ANY,
223                 .direction = UE_DIR_OUT,
224                 .bufsize = SCSI_MAX_LEN,
225                 .flags = {.ext_buffer = 1,.proxy_buffer = 1,},
226                 .callback = &bbb_data_write_callback,
227                 .timeout = 4 * USB_MS_HZ,       /* 4 seconds */
228         },
229
230         [ST_DATA_WR_CS] = {
231                 .type = UE_CONTROL,
232                 .endpoint = 0x00,       /* Control pipe */
233                 .direction = UE_DIR_ANY,
234                 .bufsize = sizeof(struct usb_device_request),
235                 .callback = &bbb_data_wr_cs_callback,
236                 .timeout = 1 * USB_MS_HZ,       /* 1 second  */
237         },
238
239         [ST_STATUS] = {
240                 .type = UE_BULK,
241                 .endpoint = UE_ADDR_ANY,
242                 .direction = UE_DIR_IN,
243                 .bufsize = sizeof(struct bbb_csw),
244                 .flags = {.short_xfer_ok = 1,},
245                 .callback = &bbb_status_callback,
246                 .timeout = 1 * USB_MS_HZ,       /* 1 second  */
247         },
248 };
249
250 static void
251 bbb_done(struct bbb_transfer *sc, int error)
252 {
253         sc->error = error;
254         sc->state = ST_COMMAND;
255         sc->status_try = 1;
256         cv_signal(&sc->cv);
257 }
258
259 static void
260 bbb_transfer_start(struct bbb_transfer *sc, uint8_t xfer_index)
261 {
262         sc->state = xfer_index;
263         usbd_transfer_start(sc->xfer[xfer_index]);
264 }
265
266 static void
267 bbb_data_clear_stall_callback(struct usb_xfer *xfer,
268     uint8_t next_xfer, uint8_t stall_xfer)
269 {
270         struct bbb_transfer *sc = usbd_xfer_softc(xfer);
271
272         if (usbd_clear_stall_callback(xfer, sc->xfer[stall_xfer])) {
273                 switch (USB_GET_STATE(xfer)) {
274                 case USB_ST_SETUP:
275                 case USB_ST_TRANSFERRED:
276                         bbb_transfer_start(sc, next_xfer);
277                         break;
278                 default:
279                         bbb_done(sc, USB_ERR_STALLED);
280                         break;
281                 }
282         }
283 }
284
285 static void
286 bbb_command_callback(struct usb_xfer *xfer, usb_error_t error)
287 {
288         struct bbb_transfer *sc = usbd_xfer_softc(xfer);
289         uint32_t tag;
290
291         switch (USB_GET_STATE(xfer)) {
292         case USB_ST_TRANSFERRED:
293                 bbb_transfer_start
294                     (sc, ((sc->dir == DIR_IN) ? ST_DATA_RD :
295                     (sc->dir == DIR_OUT) ? ST_DATA_WR :
296                     ST_STATUS));
297                 break;
298
299         case USB_ST_SETUP:
300                 sc->status_try = 0;
301                 tag = UGETDW(sc->cbw->dCBWTag) + 1;
302                 USETDW(sc->cbw->dCBWSignature, CBWSIGNATURE);
303                 USETDW(sc->cbw->dCBWTag, tag);
304                 USETDW(sc->cbw->dCBWDataTransferLength, (uint32_t)sc->data_len);
305                 sc->cbw->bCBWFlags = ((sc->dir == DIR_IN) ? CBWFLAGS_IN : CBWFLAGS_OUT);
306                 sc->cbw->bCBWLUN = sc->lun;
307                 sc->cbw->bCDBLength = sc->cmd_len;
308                 if (sc->cbw->bCDBLength > sizeof(sc->cbw->CBWCDB)) {
309                         sc->cbw->bCDBLength = sizeof(sc->cbw->CBWCDB);
310                         DPRINTFN(0, "Truncating long command\n");
311                 }
312                 usbd_xfer_set_frame_len(xfer, 0,
313                     sizeof(struct bbb_cbw));
314                 usbd_transfer_submit(xfer);
315                 break;
316
317         default:                        /* Error */
318                 bbb_done(sc, error);
319                 break;
320         }
321 }
322
323 static void
324 bbb_data_read_callback(struct usb_xfer *xfer, usb_error_t error)
325 {
326         struct bbb_transfer *sc = usbd_xfer_softc(xfer);
327         usb_frlength_t max_bulk = usbd_xfer_max_len(xfer);
328         int actlen, sumlen;
329
330         usbd_xfer_status(xfer, &actlen, &sumlen, NULL, NULL);
331
332         switch (USB_GET_STATE(xfer)) {
333         case USB_ST_TRANSFERRED:
334                 sc->data_rem -= actlen;
335                 sc->data_ptr += actlen;
336                 sc->actlen += actlen;
337
338                 if (actlen < sumlen) {
339                         /* short transfer */
340                         sc->data_rem = 0;
341                 }
342         case USB_ST_SETUP:
343                 DPRINTF("max_bulk=%d, data_rem=%d\n",
344                     max_bulk, sc->data_rem);
345
346                 if (sc->data_rem == 0) {
347                         bbb_transfer_start(sc, ST_STATUS);
348                         break;
349                 }
350                 if (max_bulk > sc->data_rem) {
351                         max_bulk = sc->data_rem;
352                 }
353                 usbd_xfer_set_timeout(xfer, sc->data_timeout);
354                 usbd_xfer_set_frame_data(xfer, 0, sc->data_ptr, max_bulk);
355                 usbd_transfer_submit(xfer);
356                 break;
357
358         default:                        /* Error */
359                 if (error == USB_ERR_CANCELLED) {
360                         bbb_done(sc, error);
361                 } else {
362                         bbb_transfer_start(sc, ST_DATA_RD_CS);
363                 }
364                 break;
365         }
366 }
367
368 static void
369 bbb_data_rd_cs_callback(struct usb_xfer *xfer, usb_error_t error)
370 {
371         bbb_data_clear_stall_callback(xfer, ST_STATUS,
372             ST_DATA_RD);
373 }
374
375 static void
376 bbb_data_write_callback(struct usb_xfer *xfer, usb_error_t error)
377 {
378         struct bbb_transfer *sc = usbd_xfer_softc(xfer);
379         usb_frlength_t max_bulk = usbd_xfer_max_len(xfer);
380         int actlen, sumlen;
381
382         usbd_xfer_status(xfer, &actlen, &sumlen, NULL, NULL);
383
384         switch (USB_GET_STATE(xfer)) {
385         case USB_ST_TRANSFERRED:
386                 sc->data_rem -= actlen;
387                 sc->data_ptr += actlen;
388                 sc->actlen += actlen;
389
390                 if (actlen < sumlen) {
391                         /* short transfer */
392                         sc->data_rem = 0;
393                 }
394         case USB_ST_SETUP:
395                 DPRINTF("max_bulk=%d, data_rem=%d\n",
396                     max_bulk, sc->data_rem);
397
398                 if (sc->data_rem == 0) {
399                         bbb_transfer_start(sc, ST_STATUS);
400                         break;
401                 }
402                 if (max_bulk > sc->data_rem) {
403                         max_bulk = sc->data_rem;
404                 }
405                 usbd_xfer_set_timeout(xfer, sc->data_timeout);
406                 usbd_xfer_set_frame_data(xfer, 0, sc->data_ptr, max_bulk);
407                 usbd_transfer_submit(xfer);
408                 break;
409
410         default:                        /* Error */
411                 if (error == USB_ERR_CANCELLED) {
412                         bbb_done(sc, error);
413                 } else {
414                         bbb_transfer_start(sc, ST_DATA_WR_CS);
415                 }
416                 break;
417         }
418 }
419
420 static void
421 bbb_data_wr_cs_callback(struct usb_xfer *xfer, usb_error_t error)
422 {
423         bbb_data_clear_stall_callback(xfer, ST_STATUS,
424             ST_DATA_WR);
425 }
426
427 static void
428 bbb_status_callback(struct usb_xfer *xfer, usb_error_t error)
429 {
430         struct bbb_transfer *sc = usbd_xfer_softc(xfer);
431         int actlen;
432         int sumlen;
433
434         usbd_xfer_status(xfer, &actlen, &sumlen, NULL, NULL);
435
436         switch (USB_GET_STATE(xfer)) {
437         case USB_ST_TRANSFERRED:
438
439                 /* very simple status check */
440
441                 if (actlen < (int)sizeof(struct bbb_csw)) {
442                         bbb_done(sc, USB_ERR_SHORT_XFER);
443                 } else if (sc->csw->bCSWStatus == CSWSTATUS_GOOD) {
444                         bbb_done(sc, 0);        /* success */
445                 } else {
446                         bbb_done(sc, ERR_CSW_FAILED);   /* error */
447                 }
448                 break;
449
450         case USB_ST_SETUP:
451                 usbd_xfer_set_frame_len(xfer, 0,
452                     sizeof(struct bbb_csw));
453                 usbd_transfer_submit(xfer);
454                 break;
455
456         default:
457                 DPRINTF("Failed to read CSW: %s, try %d\n",
458                     usbd_errstr(error), sc->status_try);
459
460                 if (error == USB_ERR_CANCELLED || sc->status_try) {
461                         bbb_done(sc, error);
462                 } else {
463                         sc->status_try = 1;
464                         bbb_transfer_start(sc, ST_DATA_RD_CS);
465                 }
466                 break;
467         }
468 }
469
470 /*------------------------------------------------------------------------*
471  *      bbb_command_start - execute a SCSI command synchronously
472  *
473  * Return values
474  * 0: Success
475  * Else: Failure
476  *------------------------------------------------------------------------*/
477 static int
478 bbb_command_start(struct bbb_transfer *sc, uint8_t dir, uint8_t lun,
479     void *data_ptr, size_t data_len, void *cmd_ptr, size_t cmd_len,
480     usb_timeout_t data_timeout)
481 {
482         sc->lun = lun;
483         sc->dir = data_len ? dir : DIR_NONE;
484         sc->data_ptr = data_ptr;
485         sc->data_len = data_len;
486         sc->data_rem = data_len;
487         sc->data_timeout = (data_timeout + USB_MS_HZ);
488         sc->actlen = 0;
489         sc->error = 0;
490         sc->cmd_len = cmd_len;
491         memset(&sc->cbw->CBWCDB, 0, sizeof(sc->cbw->CBWCDB));
492         memcpy(&sc->cbw->CBWCDB, cmd_ptr, cmd_len);
493         DPRINTFN(1, "SCSI cmd = %*D\n", (int)cmd_len, (char *)sc->cbw->CBWCDB, ":");
494
495         mtx_lock(&sc->mtx);
496         usbd_transfer_start(sc->xfer[sc->state]);
497
498         while (usbd_transfer_pending(sc->xfer[sc->state])) {
499                 cv_wait(&sc->cv, &sc->mtx);
500         }
501         mtx_unlock(&sc->mtx);
502         return (sc->error);
503 }
504
505 static struct bbb_transfer *
506 bbb_attach(struct usb_device *udev, uint8_t iface_index)
507 {
508         struct usb_interface *iface;
509         struct usb_interface_descriptor *id;
510         struct bbb_transfer *sc;
511         usb_error_t err;
512         uint8_t do_unlock;
513
514         /* Prevent re-enumeration */
515         do_unlock = usbd_enum_lock(udev);
516
517         /*
518          * Make sure any driver which is hooked up to this interface,
519          * like umass is gone:
520          */
521         usb_detach_device(udev, iface_index, 0);
522
523         if (do_unlock)
524                 usbd_enum_unlock(udev);
525
526         iface = usbd_get_iface(udev, iface_index);
527         if (iface == NULL)
528                 return (NULL);
529
530         id = iface->idesc;
531         if (id == NULL || id->bInterfaceClass != UICLASS_MASS)
532                 return (NULL);
533
534         switch (id->bInterfaceSubClass) {
535         case UISUBCLASS_SCSI:
536         case UISUBCLASS_UFI:
537         case UISUBCLASS_SFF8020I:
538         case UISUBCLASS_SFF8070I:
539                 break;
540         default:
541                 return (NULL);
542         }
543
544         switch (id->bInterfaceProtocol) {
545         case UIPROTO_MASS_BBB_OLD:
546         case UIPROTO_MASS_BBB:
547                 break;
548         default:
549                 return (NULL);
550         }
551
552         sc = malloc(sizeof(*sc), M_USB, M_WAITOK | M_ZERO);
553         mtx_init(&sc->mtx, "USB autoinstall", NULL, MTX_DEF);
554         cv_init(&sc->cv, "WBBB");
555
556         err = usbd_transfer_setup(udev, &iface_index, sc->xfer, bbb_config,
557             ST_MAX, sc, &sc->mtx);
558         if (err) {
559                 bbb_detach(sc);
560                 return (NULL);
561         }
562         /* store pointer to DMA buffers */
563         sc->buffer = usbd_xfer_get_frame_buffer(
564             sc->xfer[ST_DATA_RD], 0);
565         sc->buffer_size =
566             usbd_xfer_max_len(sc->xfer[ST_DATA_RD]);
567         sc->cbw = usbd_xfer_get_frame_buffer(
568             sc->xfer[ST_COMMAND], 0);
569         sc->csw = usbd_xfer_get_frame_buffer(
570             sc->xfer[ST_STATUS], 0);
571
572         return (sc);
573 }
574
575 static void
576 bbb_detach(struct bbb_transfer *sc)
577 {
578         usbd_transfer_unsetup(sc->xfer, ST_MAX);
579         mtx_destroy(&sc->mtx);
580         cv_destroy(&sc->cv);
581         free(sc, M_USB);
582 }
583
584 /*------------------------------------------------------------------------*
585  *      usb_iface_is_cdrom
586  *
587  * Return values:
588  * 1: This interface is an auto install disk (CD-ROM)
589  * 0: Not an auto install disk.
590  *------------------------------------------------------------------------*/
591 int
592 usb_iface_is_cdrom(struct usb_device *udev, uint8_t iface_index)
593 {
594         struct bbb_transfer *sc;
595         uint8_t timeout;
596         uint8_t is_cdrom;
597         uint8_t sid_type;
598         int err;
599
600         sc = bbb_attach(udev, iface_index);
601         if (sc == NULL)
602                 return (0);
603
604         is_cdrom = 0;
605         timeout = 4;    /* tries */
606         while (--timeout) {
607                 err = bbb_command_start(sc, DIR_IN, 0, sc->buffer,
608                     SCSI_INQ_LEN, &scsi_inquiry, sizeof(scsi_inquiry),
609                     USB_MS_HZ);
610
611                 if (err == 0 && sc->actlen > 0) {
612                         sid_type = sc->buffer[0] & 0x1F;
613                         if (sid_type == 0x05)
614                                 is_cdrom = 1;
615                         break;
616                 } else if (err != ERR_CSW_FAILED)
617                         break;  /* non retryable error */
618                 usb_pause_mtx(NULL, hz);
619         }
620         bbb_detach(sc);
621         return (is_cdrom);
622 }
623
624 static uint8_t
625 usb_msc_get_max_lun(struct usb_device *udev, uint8_t iface_index)
626 {
627         struct usb_device_request req;
628         usb_error_t err;
629         uint8_t buf = 0;
630
631
632         /* The Get Max Lun command is a class-specific request. */
633         req.bmRequestType = UT_READ_CLASS_INTERFACE;
634         req.bRequest = 0xFE;            /* GET_MAX_LUN */
635         USETW(req.wValue, 0);
636         req.wIndex[0] = iface_index;
637         req.wIndex[1] = 0;
638         USETW(req.wLength, 1);
639
640         err = usbd_do_request(udev, NULL, &req, &buf);
641         if (err)
642                 buf = 0;
643
644         return (buf);
645 }
646
647 usb_error_t
648 usb_msc_auto_quirk(struct usb_device *udev, uint8_t iface_index)
649 {
650         struct bbb_transfer *sc;
651         uint8_t timeout;
652         uint8_t is_no_direct;
653         uint8_t sid_type;
654         int err;
655
656         sc = bbb_attach(udev, iface_index);
657         if (sc == NULL)
658                 return (0);
659
660         /*
661          * Some devices need a delay after that the configuration
662          * value is set to function properly:
663          */
664         usb_pause_mtx(NULL, hz);
665
666         if (usb_msc_get_max_lun(udev, iface_index) == 0) {
667                 DPRINTF("Device has only got one LUN.\n");
668                 usbd_add_dynamic_quirk(udev, UQ_MSC_NO_GETMAXLUN);
669         }
670
671         is_no_direct = 1;
672         for (timeout = 4; timeout != 0; timeout--) {
673                 err = bbb_command_start(sc, DIR_IN, 0, sc->buffer,
674                     SCSI_INQ_LEN, &scsi_inquiry, sizeof(scsi_inquiry),
675                     USB_MS_HZ);
676
677                 if (err == 0 && sc->actlen > 0) {
678                         sid_type = sc->buffer[0] & 0x1F;
679                         if (sid_type == 0x00)
680                                 is_no_direct = 0;
681                         break;
682                 } else if (err != ERR_CSW_FAILED) {
683                         DPRINTF("Device is not responding "
684                             "properly to SCSI INQUIRY command.\n");
685                         goto error;     /* non retryable error */
686                 }
687                 usb_pause_mtx(NULL, hz);
688         }
689
690         if (is_no_direct) {
691                 DPRINTF("Device is not direct access.\n");
692                 goto done;
693         }
694
695         err = bbb_command_start(sc, DIR_IN, 0, NULL, 0,
696             &scsi_test_unit_ready, sizeof(scsi_test_unit_ready),
697             USB_MS_HZ);
698
699         if (err != 0) {
700                 if (err != ERR_CSW_FAILED)
701                         goto error;
702                 DPRINTF("Test unit ready failed\n");
703         }
704
705         err = bbb_command_start(sc, DIR_OUT, 0, NULL, 0,
706             &scsi_prevent_removal, sizeof(scsi_prevent_removal),
707             USB_MS_HZ);
708
709         if (err == 0) {
710                 err = bbb_command_start(sc, DIR_OUT, 0, NULL, 0,
711                     &scsi_allow_removal, sizeof(scsi_allow_removal),
712                     USB_MS_HZ);
713         }
714
715         if (err != 0) {
716                 if (err != ERR_CSW_FAILED)
717                         goto error;
718                 DPRINTF("Device doesn't handle prevent and allow removal\n");
719                 usbd_add_dynamic_quirk(udev, UQ_MSC_NO_PREVENT_ALLOW);
720         }
721
722         timeout = 1;
723
724 retry_sync_cache:
725         err = bbb_command_start(sc, DIR_IN, 0, NULL, 0,
726             &scsi_sync_cache, sizeof(scsi_sync_cache),
727             USB_MS_HZ);
728
729         if (err != 0) {
730
731                 if (err != ERR_CSW_FAILED)
732                         goto error;
733
734                 DPRINTF("Device doesn't handle synchronize cache\n");
735
736                 usbd_add_dynamic_quirk(udev, UQ_MSC_NO_SYNC_CACHE);
737         } else {
738
739                 /*
740                  * Certain Kingston memory sticks fail the first
741                  * read capacity after a synchronize cache command
742                  * has been issued. Disable the synchronize cache
743                  * command for such devices.
744                  */
745
746                 err = bbb_command_start(sc, DIR_IN, 0, sc->buffer, 8,
747                     &scsi_read_capacity, sizeof(scsi_read_capacity),
748                     USB_MS_HZ);
749
750                 if (err != 0) {
751                         if (err != ERR_CSW_FAILED)
752                                 goto error;
753
754                         err = bbb_command_start(sc, DIR_IN, 0, sc->buffer, 8,
755                             &scsi_read_capacity, sizeof(scsi_read_capacity),
756                             USB_MS_HZ);
757
758                         if (err == 0) {
759                                 if (timeout--)
760                                         goto retry_sync_cache;
761
762                                 DPRINTF("Device most likely doesn't "
763                                     "handle synchronize cache\n");
764
765                                 usbd_add_dynamic_quirk(udev,
766                                     UQ_MSC_NO_SYNC_CACHE);
767                         } else {
768                                 if (err != ERR_CSW_FAILED)
769                                         goto error;
770                         }
771                 }
772         }
773
774         /* clear sense status of any failed commands on the device */
775
776         err = bbb_command_start(sc, DIR_IN, 0, sc->buffer,
777             SCSI_INQ_LEN, &scsi_inquiry, sizeof(scsi_inquiry),
778             USB_MS_HZ);
779
780         DPRINTF("Inquiry = %d\n", err);
781
782         if (err != 0) {
783
784                 if (err != ERR_CSW_FAILED)
785                         goto error;
786         }
787
788         err = bbb_command_start(sc, DIR_IN, 0, sc->buffer,
789             SCSI_SENSE_LEN, &scsi_request_sense,
790             sizeof(scsi_request_sense), USB_MS_HZ);
791
792         DPRINTF("Request sense = %d\n", err);
793
794         if (err != 0) {
795
796                 if (err != ERR_CSW_FAILED)
797                         goto error;
798         }
799
800 done:
801         bbb_detach(sc);
802         return (0);
803
804 error:
805         bbb_detach(sc);
806
807         DPRINTF("Device did not respond, enabling all quirks\n");
808
809         usbd_add_dynamic_quirk(udev, UQ_MSC_NO_SYNC_CACHE);
810         usbd_add_dynamic_quirk(udev, UQ_MSC_NO_PREVENT_ALLOW);
811         usbd_add_dynamic_quirk(udev, UQ_MSC_NO_TEST_UNIT_READY);
812
813         /* Need to re-enumerate the device */
814         usbd_req_re_enumerate(udev, NULL);
815
816         return (USB_ERR_STALLED);
817 }
818
819 usb_error_t
820 usb_msc_eject(struct usb_device *udev, uint8_t iface_index, int method)
821 {
822         struct bbb_transfer *sc;
823         usb_error_t err;
824
825         sc = bbb_attach(udev, iface_index);
826         if (sc == NULL)
827                 return (USB_ERR_INVAL);
828
829         switch (method) {
830         case MSC_EJECT_STOPUNIT:
831                 err = bbb_command_start(sc, DIR_IN, 0, NULL, 0,
832                     &scsi_test_unit_ready, sizeof(scsi_test_unit_ready),
833                     USB_MS_HZ);
834                 DPRINTF("Test unit ready status: %s\n", usbd_errstr(err));
835                 err = bbb_command_start(sc, DIR_IN, 0, NULL, 0,
836                     &scsi_start_stop_unit, sizeof(scsi_start_stop_unit),
837                     USB_MS_HZ);
838                 break;
839         case MSC_EJECT_REZERO:
840                 err = bbb_command_start(sc, DIR_IN, 0, NULL, 0,
841                     &scsi_rezero_init, sizeof(scsi_rezero_init),
842                     USB_MS_HZ);
843                 break;
844         case MSC_EJECT_ZTESTOR:
845                 err = bbb_command_start(sc, DIR_IN, 0, NULL, 0,
846                     &scsi_ztestor_eject, sizeof(scsi_ztestor_eject),
847                     USB_MS_HZ);
848                 break;
849         case MSC_EJECT_CMOTECH:
850                 err = bbb_command_start(sc, DIR_IN, 0, NULL, 0,
851                     &scsi_cmotech_eject, sizeof(scsi_cmotech_eject),
852                     USB_MS_HZ);
853                 break;
854         case MSC_EJECT_HUAWEI:
855                 err = bbb_command_start(sc, DIR_IN, 0, NULL, 0,
856                     &scsi_huawei_eject, sizeof(scsi_huawei_eject),
857                     USB_MS_HZ);
858                 break;
859         case MSC_EJECT_HUAWEI2:
860                 err = bbb_command_start(sc, DIR_IN, 0, NULL, 0,
861                     &scsi_huawei_eject2, sizeof(scsi_huawei_eject2),
862                     USB_MS_HZ);
863                 break;
864         case MSC_EJECT_TCT:
865                 /*
866                  * TCTMobile needs DIR_IN flag. To get it, we
867                  * supply a dummy data with the command.
868                  */
869                 err = bbb_command_start(sc, DIR_IN, 0, sc->buffer,
870                     sc->buffer_size, &scsi_tct_eject,
871                     sizeof(scsi_tct_eject), USB_MS_HZ);
872                 break;
873         default:
874                 DPRINTF("Unknown eject method (%d)\n", method);
875                 bbb_detach(sc);
876                 return (USB_ERR_INVAL);
877         }
878
879         DPRINTF("Eject CD command status: %s\n", usbd_errstr(err));
880
881         bbb_detach(sc);
882         return (0);
883 }