e2b9bc5c31e6eca1d0f808422d67b17b7fe670ae
[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
111 #ifndef USB_MSCTEST_BULK_SIZE
112 #define USB_MSCTEST_BULK_SIZE   64      /* dummy */
113 #endif
114
115 #define ERR_CSW_FAILED          -1
116
117 /* Command Block Wrapper */
118 struct bbb_cbw {
119         uDWord  dCBWSignature;
120 #define CBWSIGNATURE    0x43425355
121         uDWord  dCBWTag;
122         uDWord  dCBWDataTransferLength;
123         uByte   bCBWFlags;
124 #define CBWFLAGS_OUT    0x00
125 #define CBWFLAGS_IN     0x80
126         uByte   bCBWLUN;
127         uByte   bCDBLength;
128 #define CBWCDBLENGTH    16
129         uByte   CBWCDB[CBWCDBLENGTH];
130 } __packed;
131
132 /* Command Status Wrapper */
133 struct bbb_csw {
134         uDWord  dCSWSignature;
135 #define CSWSIGNATURE    0x53425355
136         uDWord  dCSWTag;
137         uDWord  dCSWDataResidue;
138         uByte   bCSWStatus;
139 #define CSWSTATUS_GOOD  0x0
140 #define CSWSTATUS_FAILED        0x1
141 #define CSWSTATUS_PHASE 0x2
142 } __packed;
143
144 struct bbb_transfer {
145         struct lock lock;
146         struct cv cv;
147         struct bbb_cbw *cbw;
148         struct bbb_csw *csw;
149
150         struct usb_xfer *xfer[ST_MAX];
151
152         uint8_t *data_ptr;
153
154         usb_size_t data_len;            /* bytes */
155         usb_size_t data_rem;            /* bytes */
156         usb_timeout_t data_timeout;     /* ms */
157         usb_frlength_t actlen;          /* bytes */
158         usb_frlength_t buffer_size;     /* bytes */
159
160         uint8_t cmd_len;                /* bytes */
161         uint8_t dir;
162         uint8_t lun;
163         uint8_t state;
164         uint8_t status_try;
165         int     error;
166
167         uint8_t *buffer;
168 };
169
170 static usb_callback_t bbb_command_callback;
171 static usb_callback_t bbb_data_read_callback;
172 static usb_callback_t bbb_data_rd_cs_callback;
173 static usb_callback_t bbb_data_write_callback;
174 static usb_callback_t bbb_data_wr_cs_callback;
175 static usb_callback_t bbb_status_callback;
176
177 static void     bbb_done(struct bbb_transfer *, int);
178 static void     bbb_transfer_start(struct bbb_transfer *, uint8_t);
179 static void     bbb_data_clear_stall_callback(struct usb_xfer *, uint8_t,
180                     uint8_t);
181 static int      bbb_command_start(struct bbb_transfer *, uint8_t, uint8_t,
182                     void *, size_t, void *, size_t, usb_timeout_t);
183 static struct bbb_transfer *bbb_attach(struct usb_device *, uint8_t);
184 static void     bbb_detach(struct bbb_transfer *);
185
186 static const struct usb_config bbb_config[ST_MAX] = {
187
188         [ST_COMMAND] = {
189                 .type = UE_BULK,
190                 .endpoint = UE_ADDR_ANY,
191                 .direction = UE_DIR_OUT,
192                 .bufsize = sizeof(struct bbb_cbw),
193                 .callback = &bbb_command_callback,
194                 .timeout = 4 * USB_MS_HZ,       /* 4 seconds */
195         },
196
197         [ST_DATA_RD] = {
198                 .type = UE_BULK,
199                 .endpoint = UE_ADDR_ANY,
200                 .direction = UE_DIR_IN,
201                 .bufsize = SCSI_MAX_LEN,
202                 .flags = {.proxy_buffer = 1,.short_xfer_ok = 1,},
203                 .callback = &bbb_data_read_callback,
204                 .timeout = 4 * USB_MS_HZ,       /* 4 seconds */
205         },
206
207         [ST_DATA_RD_CS] = {
208                 .type = UE_CONTROL,
209                 .endpoint = 0x00,       /* Control pipe */
210                 .direction = UE_DIR_ANY,
211                 .bufsize = sizeof(struct usb_device_request),
212                 .callback = &bbb_data_rd_cs_callback,
213                 .timeout = 1 * USB_MS_HZ,       /* 1 second  */
214         },
215
216         [ST_DATA_WR] = {
217                 .type = UE_BULK,
218                 .endpoint = UE_ADDR_ANY,
219                 .direction = UE_DIR_OUT,
220                 .bufsize = SCSI_MAX_LEN,
221                 .flags = {.ext_buffer = 1,.proxy_buffer = 1,},
222                 .callback = &bbb_data_write_callback,
223                 .timeout = 4 * USB_MS_HZ,       /* 4 seconds */
224         },
225
226         [ST_DATA_WR_CS] = {
227                 .type = UE_CONTROL,
228                 .endpoint = 0x00,       /* Control pipe */
229                 .direction = UE_DIR_ANY,
230                 .bufsize = sizeof(struct usb_device_request),
231                 .callback = &bbb_data_wr_cs_callback,
232                 .timeout = 1 * USB_MS_HZ,       /* 1 second  */
233         },
234
235         [ST_STATUS] = {
236                 .type = UE_BULK,
237                 .endpoint = UE_ADDR_ANY,
238                 .direction = UE_DIR_IN,
239                 .bufsize = sizeof(struct bbb_csw),
240                 .flags = {.short_xfer_ok = 1,},
241                 .callback = &bbb_status_callback,
242                 .timeout = 1 * USB_MS_HZ,       /* 1 second  */
243         },
244 };
245
246 static void
247 bbb_done(struct bbb_transfer *sc, int error)
248 {
249         sc->error = error;
250         sc->state = ST_COMMAND;
251         sc->status_try = 1;
252         cv_signal(&sc->cv);
253 }
254
255 static void
256 bbb_transfer_start(struct bbb_transfer *sc, uint8_t xfer_index)
257 {
258         sc->state = xfer_index;
259         usbd_transfer_start(sc->xfer[xfer_index]);
260 }
261
262 static void
263 bbb_data_clear_stall_callback(struct usb_xfer *xfer,
264     uint8_t next_xfer, uint8_t stall_xfer)
265 {
266         struct bbb_transfer *sc = usbd_xfer_softc(xfer);
267
268         if (usbd_clear_stall_callback(xfer, sc->xfer[stall_xfer])) {
269                 switch (USB_GET_STATE(xfer)) {
270                 case USB_ST_SETUP:
271                 case USB_ST_TRANSFERRED:
272                         bbb_transfer_start(sc, next_xfer);
273                         break;
274                 default:
275                         bbb_done(sc, USB_ERR_STALLED);
276                         break;
277                 }
278         }
279 }
280
281 static void
282 bbb_command_callback(struct usb_xfer *xfer, usb_error_t error)
283 {
284         struct bbb_transfer *sc = usbd_xfer_softc(xfer);
285         uint32_t tag;
286
287         switch (USB_GET_STATE(xfer)) {
288         case USB_ST_TRANSFERRED:
289                 bbb_transfer_start
290                     (sc, ((sc->dir == DIR_IN) ? ST_DATA_RD :
291                     (sc->dir == DIR_OUT) ? ST_DATA_WR :
292                     ST_STATUS));
293                 break;
294
295         case USB_ST_SETUP:
296                 sc->status_try = 0;
297                 tag = UGETDW(sc->cbw->dCBWTag) + 1;
298                 USETDW(sc->cbw->dCBWSignature, CBWSIGNATURE);
299                 USETDW(sc->cbw->dCBWTag, tag);
300                 USETDW(sc->cbw->dCBWDataTransferLength, (uint32_t)sc->data_len);
301                 sc->cbw->bCBWFlags = ((sc->dir == DIR_IN) ? CBWFLAGS_IN : CBWFLAGS_OUT);
302                 sc->cbw->bCBWLUN = sc->lun;
303                 sc->cbw->bCDBLength = sc->cmd_len;
304                 if (sc->cbw->bCDBLength > sizeof(sc->cbw->CBWCDB)) {
305                         sc->cbw->bCDBLength = sizeof(sc->cbw->CBWCDB);
306                         DPRINTFN(0, "Truncating long command\n");
307                 }
308                 usbd_xfer_set_frame_len(xfer, 0,
309                     sizeof(struct bbb_cbw));
310                 usbd_transfer_submit(xfer);
311                 break;
312
313         default:                        /* Error */
314                 bbb_done(sc, error);
315                 break;
316         }
317 }
318
319 static void
320 bbb_data_read_callback(struct usb_xfer *xfer, usb_error_t error)
321 {
322         struct bbb_transfer *sc = usbd_xfer_softc(xfer);
323         usb_frlength_t max_bulk = usbd_xfer_max_len(xfer);
324         int actlen, sumlen;
325
326         usbd_xfer_status(xfer, &actlen, &sumlen, NULL, NULL);
327
328         switch (USB_GET_STATE(xfer)) {
329         case USB_ST_TRANSFERRED:
330                 sc->data_rem -= actlen;
331                 sc->data_ptr += actlen;
332                 sc->actlen += actlen;
333
334                 if (actlen < sumlen) {
335                         /* short transfer */
336                         sc->data_rem = 0;
337                 }
338         case USB_ST_SETUP:
339                 DPRINTF("max_bulk=%d, data_rem=%d\n",
340                     max_bulk, sc->data_rem);
341
342                 if (sc->data_rem == 0) {
343                         bbb_transfer_start(sc, ST_STATUS);
344                         break;
345                 }
346                 if (max_bulk > sc->data_rem) {
347                         max_bulk = sc->data_rem;
348                 }
349                 usbd_xfer_set_timeout(xfer, sc->data_timeout);
350                 usbd_xfer_set_frame_data(xfer, 0, sc->data_ptr, max_bulk);
351                 usbd_transfer_submit(xfer);
352                 break;
353
354         default:                        /* Error */
355                 if (error == USB_ERR_CANCELLED) {
356                         bbb_done(sc, error);
357                 } else {
358                         bbb_transfer_start(sc, ST_DATA_RD_CS);
359                 }
360                 break;
361         }
362 }
363
364 static void
365 bbb_data_rd_cs_callback(struct usb_xfer *xfer, usb_error_t error)
366 {
367         bbb_data_clear_stall_callback(xfer, ST_STATUS,
368             ST_DATA_RD);
369 }
370
371 static void
372 bbb_data_write_callback(struct usb_xfer *xfer, usb_error_t error)
373 {
374         struct bbb_transfer *sc = usbd_xfer_softc(xfer);
375         usb_frlength_t max_bulk = usbd_xfer_max_len(xfer);
376         int actlen, sumlen;
377
378         usbd_xfer_status(xfer, &actlen, &sumlen, NULL, NULL);
379
380         switch (USB_GET_STATE(xfer)) {
381         case USB_ST_TRANSFERRED:
382                 sc->data_rem -= actlen;
383                 sc->data_ptr += actlen;
384                 sc->actlen += actlen;
385
386                 if (actlen < sumlen) {
387                         /* short transfer */
388                         sc->data_rem = 0;
389                 }
390         case USB_ST_SETUP:
391                 DPRINTF("max_bulk=%d, data_rem=%d\n",
392                     max_bulk, sc->data_rem);
393
394                 if (sc->data_rem == 0) {
395                         bbb_transfer_start(sc, ST_STATUS);
396                         break;
397                 }
398                 if (max_bulk > sc->data_rem) {
399                         max_bulk = sc->data_rem;
400                 }
401                 usbd_xfer_set_timeout(xfer, sc->data_timeout);
402                 usbd_xfer_set_frame_data(xfer, 0, sc->data_ptr, max_bulk);
403                 usbd_transfer_submit(xfer);
404                 break;
405
406         default:                        /* Error */
407                 if (error == USB_ERR_CANCELLED) {
408                         bbb_done(sc, error);
409                 } else {
410                         bbb_transfer_start(sc, ST_DATA_WR_CS);
411                 }
412                 break;
413         }
414 }
415
416 static void
417 bbb_data_wr_cs_callback(struct usb_xfer *xfer, usb_error_t error)
418 {
419         bbb_data_clear_stall_callback(xfer, ST_STATUS,
420             ST_DATA_WR);
421 }
422
423 static void
424 bbb_status_callback(struct usb_xfer *xfer, usb_error_t error)
425 {
426         struct bbb_transfer *sc = usbd_xfer_softc(xfer);
427         int actlen;
428         int sumlen;
429
430         usbd_xfer_status(xfer, &actlen, &sumlen, NULL, NULL);
431
432         switch (USB_GET_STATE(xfer)) {
433         case USB_ST_TRANSFERRED:
434
435                 /* very simple status check */
436
437                 if (actlen < (int)sizeof(struct bbb_csw)) {
438                         bbb_done(sc, USB_ERR_SHORT_XFER);
439                 } else if (sc->csw->bCSWStatus == CSWSTATUS_GOOD) {
440                         bbb_done(sc, 0);        /* success */
441                 } else {
442                         bbb_done(sc, ERR_CSW_FAILED);   /* error */
443                 }
444                 break;
445
446         case USB_ST_SETUP:
447                 usbd_xfer_set_frame_len(xfer, 0,
448                     sizeof(struct bbb_csw));
449                 usbd_transfer_submit(xfer);
450                 break;
451
452         default:
453                 DPRINTF("Failed to read CSW: %s, try %d\n",
454                     usbd_errstr(error), sc->status_try);
455
456                 if (error == USB_ERR_CANCELLED || sc->status_try) {
457                         bbb_done(sc, error);
458                 } else {
459                         sc->status_try = 1;
460                         bbb_transfer_start(sc, ST_DATA_RD_CS);
461                 }
462                 break;
463         }
464 }
465
466 /*------------------------------------------------------------------------*
467  *      bbb_command_start - execute a SCSI command synchronously
468  *
469  * Return values
470  * 0: Success
471  * Else: Failure
472  *------------------------------------------------------------------------*/
473 static int
474 bbb_command_start(struct bbb_transfer *sc, uint8_t dir, uint8_t lun,
475     void *data_ptr, size_t data_len, void *cmd_ptr, size_t cmd_len,
476     usb_timeout_t data_timeout)
477 {
478         sc->lun = lun;
479         sc->dir = data_len ? dir : DIR_NONE;
480         sc->data_ptr = data_ptr;
481         sc->data_len = data_len;
482         sc->data_rem = data_len;
483         sc->data_timeout = (data_timeout + USB_MS_HZ);
484         sc->actlen = 0;
485         sc->error = 0;
486         sc->cmd_len = cmd_len;
487         memset(&sc->cbw->CBWCDB, 0, sizeof(sc->cbw->CBWCDB));
488         memcpy(&sc->cbw->CBWCDB, cmd_ptr, cmd_len);
489         DPRINTFN(1, "SCSI cmd_len = %d, cmd %s\n", (int)cmd_len, (char *)sc->cbw->CBWCDB);
490
491         lockmgr(&sc->lock, LK_EXCLUSIVE);
492         usbd_transfer_start(sc->xfer[sc->state]);
493
494         while (usbd_transfer_pending(sc->xfer[sc->state])) {
495                 cv_wait(&sc->cv, &sc->lock);
496         }
497         lockmgr(&sc->lock, LK_RELEASE);
498         return (sc->error);
499 }
500
501 static struct bbb_transfer *
502 bbb_attach(struct usb_device *udev, uint8_t iface_index)
503 {
504         struct usb_interface *iface;
505         struct usb_interface_descriptor *id;
506         struct bbb_transfer *sc;
507         usb_error_t err;
508
509 #if USB_HAVE_MSCTEST_DETACH
510         uint8_t do_unlock;
511
512         /* Prevent re-enumeration */
513         do_unlock = usbd_enum_lock(udev);
514
515         /*
516          * Make sure any driver which is hooked up to this interface,
517          * like umass is gone:
518          */
519         usb_detach_device(udev, iface_index, 0);
520
521         if (do_unlock)
522                 usbd_enum_unlock(udev);
523 #endif
524
525         iface = usbd_get_iface(udev, iface_index);
526         if (iface == NULL)
527                 return (NULL);
528
529         id = iface->idesc;
530         if (id == NULL || id->bInterfaceClass != UICLASS_MASS)
531                 return (NULL);
532
533         switch (id->bInterfaceSubClass) {
534         case UISUBCLASS_SCSI:
535         case UISUBCLASS_UFI:
536         case UISUBCLASS_SFF8020I:
537         case UISUBCLASS_SFF8070I:
538                 break;
539         default:
540                 return (NULL);
541         }
542
543         switch (id->bInterfaceProtocol) {
544         case UIPROTO_MASS_BBB_OLD:
545         case UIPROTO_MASS_BBB:
546                 break;
547         default:
548                 return (NULL);
549         }
550
551         sc = kmalloc(sizeof(*sc), M_USB, M_WAITOK | M_ZERO);
552         lockinit(&sc->lock, "USB autoinstall", 0, 0);
553         cv_init(&sc->cv, "WBBB");
554
555         err = usbd_transfer_setup(udev, &iface_index, sc->xfer, bbb_config,
556             ST_MAX, sc, &sc->lock);
557         if (err) {
558                 bbb_detach(sc);
559                 return (NULL);
560         }
561         /* store pointer to DMA buffers */
562         sc->buffer = usbd_xfer_get_frame_buffer(
563             sc->xfer[ST_DATA_RD], 0);
564         sc->buffer_size =
565             usbd_xfer_max_len(sc->xfer[ST_DATA_RD]);
566         sc->cbw = usbd_xfer_get_frame_buffer(
567             sc->xfer[ST_COMMAND], 0);
568         sc->csw = usbd_xfer_get_frame_buffer(
569             sc->xfer[ST_STATUS], 0);
570
571         return (sc);
572 }
573
574 static void
575 bbb_detach(struct bbb_transfer *sc)
576 {
577         usbd_transfer_unsetup(sc->xfer, ST_MAX);
578         lockuninit(&sc->lock);
579         cv_destroy(&sc->cv);
580         kfree(sc, M_USB);
581 }
582
583 /*------------------------------------------------------------------------*
584  *      usb_iface_is_cdrom
585  *
586  * Return values:
587  * 1: This interface is an auto install disk (CD-ROM)
588  * 0: Not an auto install disk.
589  *------------------------------------------------------------------------*/
590 int
591 usb_iface_is_cdrom(struct usb_device *udev, uint8_t iface_index)
592 {
593         struct bbb_transfer *sc;
594         uint8_t timeout;
595         uint8_t is_cdrom;
596         uint8_t sid_type;
597         int err;
598
599         sc = bbb_attach(udev, iface_index);
600         if (sc == NULL)
601                 return (0);
602
603         is_cdrom = 0;
604         timeout = 4;    /* tries */
605         while (--timeout) {
606                 err = bbb_command_start(sc, DIR_IN, 0, sc->buffer,
607                     SCSI_INQ_LEN, &scsi_inquiry, sizeof(scsi_inquiry),
608                     USB_MS_HZ);
609
610                 if (err == 0 && sc->actlen > 0) {
611                         sid_type = sc->buffer[0] & 0x1F;
612                         if (sid_type == 0x05)
613                                 is_cdrom = 1;
614                         break;
615                 } else if (err != ERR_CSW_FAILED)
616                         break;  /* non retryable error */
617                 usb_pause_mtx(NULL, hz);
618         }
619         bbb_detach(sc);
620         return (is_cdrom);
621 }
622
623 static uint8_t
624 usb_msc_get_max_lun(struct usb_device *udev, uint8_t iface_index)
625 {
626         struct usb_device_request req;
627         usb_error_t err;
628         uint8_t buf = 0;
629
630
631         /* The Get Max Lun command is a class-specific request. */
632         req.bmRequestType = UT_READ_CLASS_INTERFACE;
633         req.bRequest = 0xFE;            /* GET_MAX_LUN */
634         USETW(req.wValue, 0);
635         req.wIndex[0] = iface_index;
636         req.wIndex[1] = 0;
637         USETW(req.wLength, 1);
638
639         err = usbd_do_request(udev, NULL, &req, &buf);
640         if (err)
641                 buf = 0;
642
643         return (buf);
644 }
645
646 usb_error_t
647 usb_msc_auto_quirk(struct usb_device *udev, uint8_t iface_index)
648 {
649         struct bbb_transfer *sc;
650         uint8_t timeout;
651         uint8_t is_no_direct;
652         uint8_t sid_type;
653         int err;
654
655         sc = bbb_attach(udev, iface_index);
656         if (sc == NULL)
657                 return (0);
658
659         /*
660          * Some devices need a delay after that the configuration
661          * value is set to function properly:
662          */
663         usb_pause_mtx(NULL, hz);
664
665         if (usb_msc_get_max_lun(udev, iface_index) == 0) {
666                 DPRINTF("Device has only got one LUN.\n");
667                 usbd_add_dynamic_quirk(udev, UQ_MSC_NO_GETMAXLUN);
668         }
669
670         is_no_direct = 1;
671         for (timeout = 4; timeout != 0; timeout--) {
672                 err = bbb_command_start(sc, DIR_IN, 0, sc->buffer,
673                     SCSI_INQ_LEN, &scsi_inquiry, sizeof(scsi_inquiry),
674                     USB_MS_HZ);
675
676                 if (err == 0 && sc->actlen > 0) {
677                         sid_type = sc->buffer[0] & 0x1F;
678                         if (sid_type == 0x00)
679                                 is_no_direct = 0;
680                         break;
681                 } else if (err != ERR_CSW_FAILED) {
682                         DPRINTF("Device is not responding "
683                             "properly to SCSI INQUIRY command.\n");
684                         goto error;     /* non retryable error */
685                 }
686                 usb_pause_mtx(NULL, hz);
687         }
688
689         if (is_no_direct) {
690                 DPRINTF("Device is not direct access.\n");
691                 goto done;
692         }
693
694         err = bbb_command_start(sc, DIR_IN, 0, NULL, 0,
695             &scsi_test_unit_ready, sizeof(scsi_test_unit_ready),
696             USB_MS_HZ);
697
698         if (err != 0) {
699
700                 if (err != ERR_CSW_FAILED)
701                         goto error;
702         }
703         timeout = 1;
704
705 retry_sync_cache:
706         err = bbb_command_start(sc, DIR_IN, 0, NULL, 0,
707             &scsi_sync_cache, sizeof(scsi_sync_cache),
708             USB_MS_HZ);
709
710         if (err != 0) {
711
712                 if (err != ERR_CSW_FAILED)
713                         goto error;
714
715                 DPRINTF("Device doesn't handle synchronize cache\n");
716
717                 usbd_add_dynamic_quirk(udev, UQ_MSC_NO_SYNC_CACHE);
718
719         } else {
720
721                 /*
722                  * Certain Kingston memory sticks fail the first
723                  * read capacity after a synchronize cache command
724                  * has been issued. Disable the synchronize cache
725                  * command for such devices.
726                  */
727
728                 err = bbb_command_start(sc, DIR_IN, 0, sc->buffer, 8,
729                     &scsi_read_capacity, sizeof(scsi_read_capacity),
730                     USB_MS_HZ);
731
732                 if (err != 0) {
733                         if (err != ERR_CSW_FAILED)
734                                 goto error;
735
736                         err = bbb_command_start(sc, DIR_IN, 0, sc->buffer, 8,
737                             &scsi_read_capacity, sizeof(scsi_read_capacity),
738                             USB_MS_HZ);
739
740                         if (err == 0) {
741                                 if (timeout--)
742                                         goto retry_sync_cache;
743
744                                 DPRINTF("Device most likely doesn't "
745                                     "handle synchronize cache\n");
746
747                                 usbd_add_dynamic_quirk(udev,
748                                     UQ_MSC_NO_SYNC_CACHE);
749                         } else {
750                                 if (err != ERR_CSW_FAILED)
751                                         goto error;
752                         }
753                 }
754         }
755
756         /* clear sense status of any failed commands on the device */
757
758         err = bbb_command_start(sc, DIR_IN, 0, sc->buffer,
759             SCSI_INQ_LEN, &scsi_inquiry, sizeof(scsi_inquiry),
760             USB_MS_HZ);
761
762         DPRINTF("Inquiry = %d\n", err);
763
764         if (err != 0) {
765
766                 if (err != ERR_CSW_FAILED)
767                         goto error;
768         }
769
770         err = bbb_command_start(sc, DIR_IN, 0, sc->buffer,
771             SCSI_SENSE_LEN, &scsi_request_sense,
772             sizeof(scsi_request_sense), USB_MS_HZ);
773
774         DPRINTF("Request sense = %d\n", err);
775
776         if (err != 0) {
777
778                 if (err != ERR_CSW_FAILED)
779                         goto error;
780         }
781
782 done:
783         bbb_detach(sc);
784         return (0);
785
786 error:
787         bbb_detach(sc);
788
789         DPRINTF("Device did not respond, enabling all quirks\n");
790
791         usbd_add_dynamic_quirk(udev, UQ_MSC_NO_SYNC_CACHE);
792         usbd_add_dynamic_quirk(udev, UQ_MSC_NO_TEST_UNIT_READY);
793
794         /* Need to re-enumerate the device */
795         usbd_req_re_enumerate(udev, NULL);
796
797         return (USB_ERR_STALLED);
798 }
799
800 usb_error_t
801 usb_msc_eject(struct usb_device *udev, uint8_t iface_index, int method)
802 {
803         struct bbb_transfer *sc;
804         usb_error_t err;
805
806         sc = bbb_attach(udev, iface_index);
807         if (sc == NULL)
808                 return (USB_ERR_INVAL);
809
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_HUAWEI2:
841                 err = bbb_command_start(sc, DIR_IN, 0, NULL, 0,
842                     &scsi_huawei_eject2, sizeof(scsi_huawei_eject2),
843                     USB_MS_HZ);
844                 break;
845         case MSC_EJECT_TCT:
846                 /*
847                  * TCTMobile needs DIR_IN flag. To get it, we
848                  * supply a dummy data with the command.
849                  */
850                 err = bbb_command_start(sc, DIR_IN, 0, sc->buffer,
851                     sc->buffer_size, &scsi_tct_eject,
852                     sizeof(scsi_tct_eject), USB_MS_HZ);
853                 break;
854         default:
855                 DPRINTF("Unknown eject method (%d)\n", method);
856                 bbb_detach(sc);
857                 return (USB_ERR_INVAL);
858         }
859
860         DPRINTF("Eject CD command status: %s\n", usbd_errstr(err));
861
862         bbb_detach(sc);
863         return (0);
864 }
865
866 usb_error_t
867 usb_msc_read_10(struct usb_device *udev, uint8_t iface_index,
868     uint32_t lba, uint32_t blocks, void *buffer)
869 {
870         struct bbb_transfer *sc;
871         uint8_t cmd[10];
872         usb_error_t err;
873
874         cmd[0] = 0x28;          /* READ_10 */
875         cmd[1] = 0;
876         cmd[2] = lba >> 24;
877         cmd[3] = lba >> 16;
878         cmd[4] = lba >> 8;
879         cmd[5] = lba >> 0;
880         cmd[6] = 0;
881         cmd[7] = blocks >> 8;
882         cmd[8] = blocks;
883         cmd[9] = 0;
884
885         sc = bbb_attach(udev, iface_index);
886         if (sc == NULL)
887                 return (USB_ERR_INVAL);
888
889         err = bbb_command_start(sc, DIR_IN, 0, buffer,
890             blocks * SCSI_FIXED_BLOCK_SIZE, cmd, 10, USB_MS_HZ);
891
892         bbb_detach(sc);
893
894         return (err);
895 }
896
897 usb_error_t
898 usb_msc_write_10(struct usb_device *udev, uint8_t iface_index,
899     uint32_t lba, uint32_t blocks, void *buffer)
900 {
901         struct bbb_transfer *sc;
902         uint8_t cmd[10];
903         usb_error_t err;
904
905         cmd[0] = 0x2a;          /* WRITE_10 */
906         cmd[1] = 0;
907         cmd[2] = lba >> 24;
908         cmd[3] = lba >> 16;
909         cmd[4] = lba >> 8;
910         cmd[5] = lba >> 0;
911         cmd[6] = 0;
912         cmd[7] = blocks >> 8;
913         cmd[8] = blocks;
914         cmd[9] = 0;
915
916         sc = bbb_attach(udev, iface_index);
917         if (sc == NULL)
918                 return (USB_ERR_INVAL);
919
920         err = bbb_command_start(sc, DIR_OUT, 0, buffer,
921             blocks * SCSI_FIXED_BLOCK_SIZE, cmd, 10, USB_MS_HZ);
922
923         bbb_detach(sc);
924
925         return (err);
926 }
927
928 usb_error_t
929 usb_msc_read_capacity(struct usb_device *udev, uint8_t iface_index,
930     uint32_t *lba_last, uint32_t *block_size)
931 {
932         struct bbb_transfer *sc;
933         usb_error_t err;
934
935         sc = bbb_attach(udev, iface_index);
936         if (sc == NULL)
937                 return (USB_ERR_INVAL);
938
939         err = bbb_command_start(sc, DIR_IN, 0, sc->buffer, 8,
940             &scsi_read_capacity, sizeof(scsi_read_capacity),
941             USB_MS_HZ);
942
943         *lba_last =
944             (sc->buffer[0] << 24) | 
945             (sc->buffer[1] << 16) |
946             (sc->buffer[2] << 8) |
947             (sc->buffer[3]);
948
949         *block_size =
950             (sc->buffer[4] << 24) | 
951             (sc->buffer[5] << 16) |
952             (sc->buffer[6] << 8) |
953             (sc->buffer[7]);
954
955         /* we currently only support one block size */
956         if (*block_size != SCSI_FIXED_BLOCK_SIZE)
957                 err = USB_ERR_INVAL;
958
959         bbb_detach(sc);
960
961         return (err);
962 }