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