]> CyberLeo.Net >> Repos - FreeBSD/FreeBSD.git/blob - sys/dev/ata/ata-usb.c
This commit was generated by cvs2svn to compensate for changes in r170242,
[FreeBSD/FreeBSD.git] / sys / dev / ata / ata-usb.c
1 /*-
2  * Copyright (c) 2006 - 2007 Søren Schmidt <sos@FreeBSD.org>
3  * 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  *    without modification, immediately at the beginning of the file.
11  * 2. Redistributions in binary form must reproduce the above copyright
12  *    notice, this list of conditions and the following disclaimer in the
13  *    documentation and/or other materials provided with the distribution.
14  *
15  * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
16  * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
17  * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
18  * IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
19  * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
20  * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
21  * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
22  * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
23  * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
24  * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
25  */
26
27 #include <sys/cdefs.h>
28 __FBSDID("$FreeBSD$");
29
30 #include "opt_ata.h"
31 #include <sys/param.h>
32 #include <sys/conf.h>
33 #include <sys/systm.h>
34 #include <sys/kernel.h>
35 #include <sys/mutex.h>
36 #include <sys/ata.h>
37 #include <sys/bus.h>
38 #include <sys/endian.h>
39 #include <sys/sysctl.h>
40 #include <sys/malloc.h>
41 #include <sys/module.h>
42 #include <sys/sema.h>
43 #include <sys/taskqueue.h>
44 #include <vm/uma.h>
45 #include <machine/resource.h>
46 #include <machine/bus.h>
47 #include <sys/rman.h>
48 #include <dev/usb/usb.h>
49 #include <dev/usb/usbdi.h>
50 #include <dev/usb/usbdi_util.h>
51 #include <dev/usb/usbdivar.h>
52 #include <dev/ata/ata-all.h>
53 #include <ata_if.h>
54
55 /* Command Block Wrapper */
56 struct bbb_cbw {
57     u_int8_t    signature[4];
58 #define         CBWSIGNATURE            0x43425355
59
60     u_int8_t    tag[4];
61     u_int8_t    transfer_length[4];
62     u_int8_t    flags;
63 #define         CBWFLAGS_OUT            0x00
64 #define         CBWFLAGS_IN             0x80
65
66     u_int8_t    lun;
67     u_int8_t    length;
68 #define         CBWCDBLENGTH            16
69
70     u_int8_t    cdb[CBWCDBLENGTH];
71 };
72
73 /* Command Status Wrapper */
74 struct bbb_csw {
75     u_int8_t    signature[4];
76 #define         CSWSIGNATURE            0x53425355
77
78     u_int8_t    tag[4];
79     u_int8_t    residue[4];
80     u_int8_t    status;
81 #define         CSWSTATUS_GOOD          0x0
82 #define         CSWSTATUS_FAILED        0x1
83 #define         CSWSTATUS_PHASE         0x2
84 };
85
86 /* USB-ATA 'controller' softc */
87 struct atausb_softc {
88     device_t            dev;            /* base device */
89     usbd_interface_handle iface;        /* interface */
90     int                 ifaceno;        /* interface number */
91     u_int8_t            bulkin;         /* endpoint address's */
92     u_int8_t            bulkout;        
93     u_int8_t            bulkirq;        
94     usbd_pipe_handle    bulkin_pipe;    /* pipe handle's */
95     usbd_pipe_handle    bulkout_pipe;
96     usbd_pipe_handle    bulkirq_pipe;
97     int                 maxlun;
98     int                 timeout;
99     struct ata_request  *ata_request;
100     usb_device_request_t usb_request;
101     struct bbb_cbw      cbw;
102     struct bbb_csw      csw;
103
104 #define ATAUSB_T_BBB_CBW                0
105 #define ATAUSB_T_BBB_DATA               1
106 #define ATAUSB_T_BBB_DCLEAR             2
107 #define ATAUSB_T_BBB_CSW1               3
108 #define ATAUSB_T_BBB_CSW2               4
109 #define ATAUSB_T_BBB_SCLEAR             5
110 #define ATAUSB_T_BBB_RESET1             6
111 #define ATAUSB_T_BBB_RESET2             7
112 #define ATAUSB_T_BBB_RESET3             8
113 #define ATAUSB_T_MAX                    9
114     usbd_xfer_handle    transfer[ATAUSB_T_MAX];
115
116     int                 state;
117 #define ATAUSB_S_ATTACH                 0
118 #define ATAUSB_S_IDLE                   1
119 #define ATAUSB_S_BBB_COMMAND            2
120 #define ATAUSB_S_BBB_DATA               3
121 #define ATAUSB_S_BBB_DCLEAR             4
122 #define ATAUSB_S_BBB_STATUS1            5
123 #define ATAUSB_S_BBB_SCLEAR             6
124 #define ATAUSB_S_BBB_STATUS2            7
125 #define ATAUSB_S_BBB_RESET1             8
126 #define ATAUSB_S_BBB_RESET2             9
127 #define ATAUSB_S_BBB_RESET3             10
128 #define ATAUSB_S_DETACH                 11
129
130     struct mtx          locked_mtx;
131     struct ata_channel  *locked_ch;
132     struct ata_channel  *restart_ch;
133 };
134
135 static int atausbdebug = 0;
136
137 /* prototypes*/
138 static usbd_status atausb_start(struct atausb_softc *sc, usbd_pipe_handle pipe, void *buffer, int buflen, int flags, usbd_xfer_handle xfer);
139 static usbd_status atausb_ctl_start(struct atausb_softc *sc, usbd_device_handle udev, usb_device_request_t *req, void *buffer, int buflen, int flags, usbd_xfer_handle xfer);
140 static void atausb_clear_stall(struct atausb_softc *sc, u_int8_t endpt, usbd_pipe_handle pipe, int state, usbd_xfer_handle xfer);
141 static void atausb_bbb_reset(struct atausb_softc *sc);
142 static int atausb_bbb_start(struct ata_request *request);
143 static void atausb_bbb_finish(usbd_xfer_handle xfer, usbd_private_handle priv, usbd_status err);
144 int ata_usbchannel_begin_transaction(struct ata_request *request);
145 int ata_usbchannel_end_transaction(struct ata_request *request);
146
147
148 /*
149  * USB frontend part
150  */
151 USB_DECLARE_DRIVER(atausb);
152 DRIVER_MODULE(atausb, uhub, atausb_driver, atausb_devclass, 0, 0);
153 MODULE_VERSION(atausb, 1);
154
155 static int
156 atausb_match(device_t dev)
157 {
158     struct usb_attach_arg *uaa = device_get_ivars(dev);
159     usb_interface_descriptor_t *id;
160
161     if (uaa->iface == NULL)
162         return UMATCH_NONE;
163
164     id = usbd_get_interface_descriptor(uaa->iface);
165     if (!id || id->bInterfaceClass != UICLASS_MASS)
166         return UMATCH_NONE;
167
168     switch (id->bInterfaceSubClass) {
169     case UISUBCLASS_QIC157:
170     case UISUBCLASS_RBC:
171     case UISUBCLASS_SCSI:
172     case UISUBCLASS_SFF8020I:
173     case UISUBCLASS_SFF8070I:
174     case UISUBCLASS_UFI:
175         switch (id->bInterfaceProtocol) {
176         case UIPROTO_MASS_CBI:
177         case UIPROTO_MASS_CBI_I:
178         case UIPROTO_MASS_BBB:
179         case UIPROTO_MASS_BBB_OLD:
180             return UMATCH_IFACECLASS_IFACESUBCLASS_IFACEPROTO;
181         default:
182             return UMATCH_IFACECLASS_IFACESUBCLASS;
183         }
184         break;
185     default:
186         return UMATCH_IFACECLASS;
187     }
188 }
189
190 static int
191 atausb_attach(device_t dev)
192 {
193     struct atausb_softc *sc = device_get_softc(dev);
194     struct usb_attach_arg *uaa = device_get_ivars(dev);
195     usb_interface_descriptor_t *id;
196     usb_endpoint_descriptor_t *ed;
197     usbd_device_handle udev;
198     usb_device_request_t request;
199     char devinfo[1024], *proto, *subclass;
200     u_int8_t maxlun;
201     int err, i;
202
203     sc->dev = dev;
204     usbd_devinfo(uaa->device, 0, devinfo);
205     device_set_desc_copy(dev, devinfo);
206     sc->bulkin = sc->bulkout = sc->bulkirq = -1;
207     sc->bulkin_pipe = sc->bulkout_pipe= sc->bulkirq_pipe = NULL;
208     sc->iface = uaa->iface;
209     sc->ifaceno = uaa->ifaceno;
210     sc->maxlun = 0;
211     sc->timeout = 5000;
212     sc->locked_ch = NULL;
213     sc->restart_ch = NULL;
214     mtx_init(&sc->locked_mtx, "ATAUSB lock", NULL, MTX_DEF); 
215
216     id = usbd_get_interface_descriptor(sc->iface);
217     switch (id->bInterfaceProtocol) {
218     case UIPROTO_MASS_BBB:
219     case UIPROTO_MASS_BBB_OLD:
220             proto = "Bulk-Only";
221             break;
222     case UIPROTO_MASS_CBI:
223             proto = "CBI";
224             break;
225     case UIPROTO_MASS_CBI_I:
226             proto = "CBI with CCI";
227             break;
228     default:
229             proto = "Unknown";
230     }
231     switch (id->bInterfaceSubClass) {
232     case UISUBCLASS_RBC:
233             subclass = "RBC";
234             break;
235     case UISUBCLASS_QIC157:
236     case UISUBCLASS_SFF8020I:
237     case UISUBCLASS_SFF8070I:
238             subclass = "ATAPI";
239             break;
240     case UISUBCLASS_SCSI:
241             subclass = "SCSI";
242             break;
243     case UISUBCLASS_UFI:
244             subclass = "UFI";
245             break;
246     default:
247             subclass = "Unknown";
248     }
249     device_printf(dev, "using %s over %s\n", subclass, proto);
250     if (strcmp(proto, "Bulk-Only") ||
251         (strcmp(subclass, "ATAPI") && strcmp(subclass, "SCSI")))
252         return ENXIO;
253
254     for (i = 0 ; i < id->bNumEndpoints ; i++) {
255         if (!(ed = usbd_interface2endpoint_descriptor(sc->iface, i))) {
256             device_printf(sc->dev, "could not read endpoint descriptor\n");
257             return ENXIO;
258         }
259         if (UE_GET_DIR(ed->bEndpointAddress) == UE_DIR_IN &&
260             (ed->bmAttributes & UE_XFERTYPE) == UE_BULK) {
261             sc->bulkin = ed->bEndpointAddress;
262         }
263         if (UE_GET_DIR(ed->bEndpointAddress) == UE_DIR_OUT &&
264                    (ed->bmAttributes & UE_XFERTYPE) == UE_BULK) {
265             sc->bulkout = ed->bEndpointAddress;
266         }
267         if (id->bInterfaceProtocol == UIPROTO_MASS_CBI_I &&
268                    UE_GET_DIR(ed->bEndpointAddress) == UE_DIR_IN &&
269                    (ed->bmAttributes & UE_XFERTYPE) == UE_INTERRUPT) {
270             sc->bulkirq = ed->bEndpointAddress;
271         }
272     }
273
274     /* check whether we found at least the endpoints we need */
275     if (!sc->bulkin || !sc->bulkout) {
276         device_printf(sc->dev, "needed endpoints not found (%d,%d)\n",
277                       sc->bulkin, sc->bulkout);
278         atausb_detach(dev);
279         return ENXIO;
280     }
281
282     /* open the pipes */
283     if (usbd_open_pipe(sc->iface, sc->bulkout,
284                        USBD_EXCLUSIVE_USE, &sc->bulkout_pipe)) {
285         device_printf(sc->dev, "cannot open bulkout pipe (%d)\n", sc->bulkout);
286         atausb_detach(dev);
287         return ENXIO;
288     }
289     if (usbd_open_pipe(sc->iface, sc->bulkin,
290                        USBD_EXCLUSIVE_USE, &sc->bulkin_pipe)) {
291         device_printf(sc->dev, "cannot open bulkin pipe (%d)\n", sc->bulkin);
292         atausb_detach(dev);
293         return ENXIO;
294     }
295     if (id->bInterfaceProtocol == UIPROTO_MASS_CBI_I) {
296         if (usbd_open_pipe(sc->iface, sc->bulkirq,
297                            USBD_EXCLUSIVE_USE, &sc->bulkirq_pipe)) {
298             device_printf(sc->dev, "cannot open bulkirq pipe (%d)\n",
299                           sc->bulkirq);
300             atausb_detach(dev);
301             return ENXIO;
302         }
303     }
304     sc->state = ATAUSB_S_ATTACH;
305
306     /* alloc needed number of transfer handles */
307     for (i = 0; i < ATAUSB_T_MAX; i++) {
308         sc->transfer[i] = usbd_alloc_xfer(uaa->device);
309         if (!sc->transfer[i]) {
310             device_printf(sc->dev, "out of memory\n");
311             atausb_detach(dev);
312             return ENXIO;
313         }
314     }
315
316     /* driver is ready to process requests here */
317     sc->state = ATAUSB_S_IDLE;
318
319     /* get number of devices so we can add matching channels */
320     usbd_interface2device_handle(sc->iface, &udev);
321     request.bmRequestType = UT_READ_CLASS_INTERFACE;
322     request.bRequest = 0xfe; //GET_MAX_LUN;
323     USETW(request.wValue, 0);
324     USETW(request.wIndex, sc->ifaceno);
325     USETW(request.wLength, sizeof(maxlun));
326     switch ((err = usbd_do_request(udev, &request, &maxlun))) {
327     case USBD_NORMAL_COMPLETION:
328         if (bootverbose)
329             device_printf(sc->dev, "maxlun=%d\n", maxlun);
330         sc->maxlun = maxlun;
331         break;
332     default:
333         if (bootverbose)
334             device_printf(sc->dev, "get maxlun not supported %s\n",
335         usbd_errstr(err));
336     }
337
338     /* ata channels are children to this USB control device */
339     for (i = 0; i <= sc->maxlun; i++) {
340         if (!device_add_child(sc->dev, "ata",
341                               devclass_find_free_unit(ata_devclass, 2))) {
342             device_printf(sc->dev, "failed to attach ata child device\n");
343             atausb_detach(dev);
344             return ENXIO;
345         }
346     }
347     bus_generic_attach(sc->dev);
348     return 0;
349 }
350
351 static int
352 atausb_detach(device_t dev)
353 {
354     struct atausb_softc *sc = device_get_softc(dev);
355     usbd_device_handle udev;
356     device_t *children;
357     int nchildren, i;
358
359     /* signal that device is going away */
360     sc->state = ATAUSB_S_DETACH;
361
362     /* abort all the pipes in case there are active transfers */
363     usbd_interface2device_handle(sc->iface, &udev);
364     usbd_abort_default_pipe(udev);
365     if (sc->bulkout_pipe)
366         usbd_abort_pipe(sc->bulkout_pipe);
367     if (sc->bulkin_pipe)
368         usbd_abort_pipe(sc->bulkin_pipe);
369     if (sc->bulkirq_pipe)
370         usbd_abort_pipe(sc->bulkirq_pipe);
371
372     /* detach & delete all children */
373     if (!device_get_children(dev, &children, &nchildren)) {
374         for (i = 0; i < nchildren; i++)
375             device_delete_child(dev, children[i]);
376         free(children, M_TEMP);
377     }
378
379     /* free the transfers */
380     for (i = 0; i < ATAUSB_T_MAX; i++)
381         if (sc->transfer[i])
382             usbd_free_xfer(sc->transfer[i]);
383
384     /* remove all the pipes */
385     if (sc->bulkout_pipe)
386         usbd_close_pipe(sc->bulkout_pipe);
387     if (sc->bulkin_pipe)
388         usbd_close_pipe(sc->bulkin_pipe);
389     if (sc->bulkirq_pipe)
390         usbd_close_pipe(sc->bulkirq_pipe);
391
392     mtx_destroy(&sc->locked_mtx);
393     return 0;
394 }
395
396
397 /*
398  * Generic USB transfer routines 
399  */
400 static usbd_status
401 atausb_start(struct atausb_softc *sc, usbd_pipe_handle pipe,
402              void *buffer, int buflen, int flags, usbd_xfer_handle xfer)
403 {
404     usbd_status err;
405
406     if (sc->state == ATAUSB_S_DETACH)
407         return USBD_NOT_STARTED;
408
409     usbd_setup_xfer(xfer, pipe, (void *)sc, buffer, buflen, flags,
410                     sc->timeout, atausb_bbb_finish);
411     err = usbd_transfer(xfer);
412     if (err && (err != USBD_IN_PROGRESS)) {
413         if (atausbdebug)
414             device_printf(sc->dev, "failed to setup transfer, %s\n",
415                           usbd_errstr(err));
416         return err;
417     }
418     return USBD_NORMAL_COMPLETION;
419 }
420
421 static usbd_status
422 atausb_ctl_start(struct atausb_softc *sc, usbd_device_handle udev,
423                  usb_device_request_t *req, void *buffer, int buflen, int flags,
424                  usbd_xfer_handle xfer)
425 {
426     usbd_status err;
427
428     if (sc->state == ATAUSB_S_DETACH)
429         return USBD_NOT_STARTED;
430
431     usbd_setup_default_xfer(xfer, udev, (void *)sc, sc->timeout, req,
432                             buffer, buflen, flags, atausb_bbb_finish);
433     err = usbd_transfer(xfer);
434     if (err && (err != USBD_IN_PROGRESS)) {
435         if (atausbdebug)
436             device_printf(sc->dev, "failed to setup ctl transfer, %s\n",
437                           usbd_errstr(err));
438         return err;
439     }
440     return USBD_NORMAL_COMPLETION;
441 }
442
443 static void
444 atausb_clear_stall(struct atausb_softc *sc, u_int8_t endpt,
445                    usbd_pipe_handle pipe, int state, usbd_xfer_handle xfer)
446 {
447     usbd_device_handle udev;
448
449     if (atausbdebug)
450         device_printf(sc->dev, "clear endpoint 0x%02x stall\n", endpt);
451     usbd_interface2device_handle(sc->iface, &udev);
452     sc->state = state;
453     usbd_clear_endpoint_toggle(pipe);
454     sc->usb_request.bmRequestType = UT_WRITE_ENDPOINT;
455     sc->usb_request.bRequest = UR_CLEAR_FEATURE;
456     USETW(sc->usb_request.wValue, UF_ENDPOINT_HALT);
457     USETW(sc->usb_request.wIndex, endpt);
458     USETW(sc->usb_request.wLength, 0);
459     atausb_ctl_start(sc, udev, &sc->usb_request, NULL, 0, 0, xfer);
460 }
461
462
463 /*
464  * Bulk-Only transport part
465  */
466 static void
467 atausb_bbb_reset(struct atausb_softc *sc)
468 {
469     usbd_device_handle udev;
470
471     if (atausbdebug)
472         device_printf(sc->dev, "Bulk Reset\n");
473     sc->timeout = 5000;
474     sc->state = ATAUSB_S_BBB_RESET1;
475     usbd_interface2device_handle(sc->iface, &udev);
476     sc->usb_request.bmRequestType = UT_WRITE_CLASS_INTERFACE;
477     sc->usb_request.bRequest = 0xff; /* bulk-only reset */
478     USETW(sc->usb_request.wValue, 0);
479     USETW(sc->usb_request.wIndex, sc->ifaceno);
480     USETW(sc->usb_request.wLength, 0);
481     atausb_ctl_start(sc, udev, &sc->usb_request, NULL,
482                      0, 0, sc->transfer[ATAUSB_T_BBB_RESET1]);
483 }
484
485 static int
486 atausb_bbb_start(struct ata_request *request)
487 {
488     struct atausb_softc *sc = 
489         device_get_softc(device_get_parent(request->parent));
490     struct ata_channel *ch = device_get_softc(request->parent);
491
492     sc->timeout = (request->timeout * 1000) + 5000;
493     USETDW(sc->cbw.signature, CBWSIGNATURE);
494     USETDW(sc->cbw.tag, UGETDW(sc->cbw.tag) + 1);
495     USETDW(sc->cbw.transfer_length, request->bytecount);
496     sc->cbw.flags = (request->flags & ATA_R_READ) ? CBWFLAGS_IN : CBWFLAGS_OUT;
497     sc->cbw.lun = ch->unit;
498     sc->cbw.length = 16;
499     bzero(sc->cbw.cdb, 16);
500     bcopy(request->u.atapi.ccb, sc->cbw.cdb, 12); /* XXX SOS */
501     sc->state = ATAUSB_S_BBB_COMMAND;
502     if (atausb_start(sc, sc->bulkout_pipe, &sc->cbw, sizeof(struct bbb_cbw),
503                      0, sc->transfer[ATAUSB_T_BBB_CBW])) {
504         request->result = EIO;
505         if (atausbdebug)
506             device_printf(request->dev, "cannot setup USB transfer\n");
507         atausb_bbb_reset(sc);
508         return ATA_OP_FINISHED;
509     }
510     return ATA_OP_CONTINUES;
511 }
512
513 static void
514 atausb_bbb_finish(usbd_xfer_handle xfer, usbd_private_handle priv,
515                  usbd_status err)
516 {
517     struct atausb_softc *sc = (struct atausb_softc *)priv;
518     struct ata_request *request = sc->ata_request;
519     usbd_xfer_handle next_xfer;
520
521     //device_printf(sc->dev, "BBB state %d: %s\n", sc->state, usbd_errstr(err));
522
523     if (sc->state == ATAUSB_S_DETACH) {
524         device_printf(sc->dev, "WARNING - device has been removed\n");
525         return;
526     }
527
528     switch (sc->state) {
529     case ATAUSB_S_BBB_COMMAND:  /* command transport phase */
530         if (err) {
531             if (atausbdebug)
532                 device_printf(sc->dev, "failed to send CBW\n");
533             request->result = EIO;
534             atausb_bbb_reset(sc);
535             return;
536         }
537
538         /* next is data transport phase, setup transfer */
539         sc->state = ATAUSB_S_BBB_DATA;
540         if (request->flags & ATA_R_READ) {
541             if (atausb_start(sc, sc->bulkin_pipe,
542                              request->data, request->bytecount,
543                              USBD_SHORT_XFER_OK,
544                              sc->transfer[ATAUSB_T_BBB_DATA])) {
545                 request->result = EIO;
546                 atausb_bbb_reset(sc);
547             }
548             return;
549         }
550         if (request->flags & ATA_R_WRITE) {
551             if (atausb_start(sc, sc->bulkout_pipe,
552                              request->data, request->bytecount,
553                              0, sc->transfer[ATAUSB_T_BBB_DATA])) {
554                 request->result = EIO;
555                 atausb_bbb_reset(sc);
556             }
557             return;
558         }
559         /* FALLTHROUGH */
560
561     case ATAUSB_S_BBB_DATA:     /* data transport phase */
562         if (request->flags & (ATA_R_READ | ATA_R_WRITE)) {
563             usbd_get_xfer_status(xfer, NULL, NULL, &request->donecount, NULL);
564             if (err) {
565                 if (atausbdebug)
566                     device_printf(sc->dev, "data %s count %d failed: %s\n",
567                                   (request->flags & ATA_R_READ?"read":"write"),
568                                   request->bytecount, usbd_errstr(err));
569                 if (err == USBD_STALLED) {
570                     atausb_clear_stall(sc,
571                                        (request->flags & ATA_R_READ ?
572                                         sc->bulkin : sc->bulkout),
573                                        (request->flags & ATA_R_READ ?
574                                         sc->bulkin_pipe : sc->bulkout_pipe),
575                                        ATAUSB_S_BBB_DCLEAR,
576                                        sc->transfer[ATAUSB_T_BBB_DCLEAR]);
577                 }
578                 else {
579                     request->result = EIO;
580                     atausb_bbb_reset(sc);
581                 }
582                 return;
583             }
584         }
585         /* FALLTHROUGH */
586
587     case ATAUSB_S_BBB_DCLEAR:   /* stall clear after data phase */
588     case ATAUSB_S_BBB_SCLEAR:   /* stall clear after status phase */
589         if (err) {
590             if (atausbdebug)
591                 device_printf(sc->dev, "bulk%s stall clear failed %s\n",
592                               (request->flags & ATA_R_READ ? "in" : "out"),
593                               usbd_errstr(err));
594             request->result = EIO;
595             atausb_bbb_reset(sc);
596             return;
597         }
598
599         if (sc->state == ATAUSB_S_BBB_COMMAND ||
600             sc->state == ATAUSB_S_BBB_DATA ||
601             sc->state == ATAUSB_S_BBB_DCLEAR) {
602             /* first attempt on status transport phase setup transfer */
603             sc->state = ATAUSB_S_BBB_STATUS1;
604             next_xfer = sc->transfer[ATAUSB_T_BBB_CSW1];
605         }
606         else {
607             /* second attempt of fetching status */
608             sc->state = ATAUSB_S_BBB_STATUS2;
609             next_xfer = sc->transfer[ATAUSB_T_BBB_CSW2];
610         }
611         if (atausb_start(sc, sc->bulkin_pipe, &sc->csw, sizeof(struct bbb_csw),
612                          USBD_SHORT_XFER_OK, next_xfer)) {
613             request->result = EIO;
614             atausb_bbb_reset(sc);
615         }
616         return;
617
618     case ATAUSB_S_BBB_STATUS1:  /* status transfer first attempt */
619     case ATAUSB_S_BBB_STATUS2:  /* status transfer second attempt */
620         if (err) {
621             if (atausbdebug)
622                 device_printf(sc->dev, "cannot get CSW, %s%s\n",
623                               usbd_errstr(err),
624                               sc->state == ATAUSB_S_BBB_STATUS1 ? ", retry":"");
625             if (sc->state == ATAUSB_S_BBB_STATUS1) {
626                 atausb_clear_stall(sc, sc->bulkin, sc->bulkin_pipe,
627                                    ATAUSB_S_BBB_SCLEAR,
628                                    sc->transfer[ATAUSB_T_BBB_SCLEAR]);
629             }
630             else {
631                 request->result = EIO;
632                 atausb_bbb_reset(sc);
633             }
634             return;
635         }
636
637         int residue = UGETDW(sc->csw.residue);
638
639         if (!residue &&
640             (request->bytecount - request->donecount))
641             residue = request->bytecount - request->donecount;
642
643         /* check CSW and handle eventual error */
644         if (UGETDW(sc->csw.signature) != CSWSIGNATURE) {
645             if (atausbdebug)
646                 device_printf(sc->dev, "bad CSW signature 0x%08x != 0x%08x\n",
647                               UGETDW(sc->csw.signature), CSWSIGNATURE);
648             request->result = EIO;
649             atausb_bbb_reset(sc);
650             return;
651         }
652         else if (UGETDW(sc->csw.tag) != UGETDW(sc->cbw.tag)) {
653             if (atausbdebug)
654                 device_printf(sc->dev, "bad CSW tag %d != %d\n",
655                               UGETDW(sc->csw.tag), UGETDW(sc->cbw.tag));
656             request->result = EIO;
657             atausb_bbb_reset(sc);
658             return;
659         }
660         else if (sc->csw.status > CSWSTATUS_PHASE) {
661             if (atausbdebug)
662                 device_printf(sc->dev, "bad CSW status %d > %d\n",
663                               sc->csw.status, CSWSTATUS_PHASE);
664             request->result = EIO;
665             atausb_bbb_reset(sc);
666             return;
667         }
668         else if (sc->csw.status == CSWSTATUS_PHASE) {
669             if (atausbdebug)
670                 device_printf(sc->dev, "phase error residue = %d\n", residue);
671             request->result = EIO;
672             atausb_bbb_reset(sc);
673             return;
674         }
675         else if (request->donecount > request->bytecount) {
676             if (atausbdebug)
677                 device_printf(sc->dev, "buffer overrun %d > %d",
678                              request->donecount, request->bytecount);
679             request->result = EIO;
680             atausb_bbb_reset(sc);
681             return;
682         }
683         else if (sc->csw.status == CSWSTATUS_FAILED) {
684             if (atausbdebug)
685                 device_printf(sc->dev, "CSWSTATUS_FAILED\n");
686             request->error = ATA_E_ATAPI_SENSE_MASK ;
687             sc->state = ATAUSB_S_IDLE;
688             ata_interrupt(device_get_softc(request->parent));
689             return;
690         }
691         else {
692             sc->state = ATAUSB_S_IDLE;
693             ata_interrupt(device_get_softc(request->parent));
694             return;
695         }
696         /* NOT REACHED */
697
698     case ATAUSB_S_BBB_RESET1:
699         if (err)
700             if (atausbdebug)
701                 device_printf(sc->dev,
702                               "BBB reset failure: %s\n", usbd_errstr(err));
703         atausb_clear_stall(sc, sc->bulkin, sc->bulkin_pipe,
704                            ATAUSB_S_BBB_RESET2,
705                            sc->transfer[ATAUSB_T_BBB_RESET2]);
706         return;
707
708     case ATAUSB_S_BBB_RESET2:
709         if (err)
710             if (atausbdebug)
711                 device_printf(sc->dev, "BBB bulkin clear stall failure: %s\n",
712                               usbd_errstr(err));
713         atausb_clear_stall(sc, sc->bulkout, sc->bulkout_pipe,
714                            ATAUSB_S_BBB_RESET3,
715                            sc->transfer[ATAUSB_T_BBB_RESET3]);
716         return;
717
718     case ATAUSB_S_BBB_RESET3:
719         if (err)
720             if (atausbdebug)
721                 device_printf(sc->dev, "BBB bulk-out clear stall failure: %s\n",
722                               usbd_errstr(err));
723         sc->state = ATAUSB_S_IDLE;
724         if (request) {
725             if (err)
726                 request->result = ENXIO;
727             else
728                 request->result = EIO;
729             ata_interrupt(device_get_softc(request->parent));
730         }
731         return;
732
733     default:
734         if (atausbdebug)
735             device_printf(sc->dev, "unknown state %d", sc->state);
736     }
737 }
738
739
740 /*
741  * ATA backend part
742  */
743 struct atapi_inquiry {
744     u_int8_t    device_type;
745     u_int8_t    device_modifier;
746     u_int8_t    version;
747     u_int8_t    response_format;
748     u_int8_t    length;
749     u_int8_t    reserved[2];
750     u_int8_t    flags;
751     u_int8_t    vendor[8];
752     u_int8_t    product[16];
753     u_int8_t    revision[4];
754     //u_int8_t    crap[60];
755 };
756
757 int
758 ata_usbchannel_begin_transaction(struct ata_request *request)
759 {
760     struct atausb_softc *sc = 
761         device_get_softc(device_get_parent(request->parent));
762
763     if (atausbdebug > 1)
764         device_printf(request->dev, "begin_transaction %s\n",
765                       ata_cmd2str(request));
766
767     /* sanity just in case */
768     if (sc->state != ATAUSB_S_IDLE) {
769         printf("begin is busy (%d)\n", sc->state);
770         request->result = EBUSY;
771         return ATA_OP_FINISHED;
772     }
773
774     /* XXX SOS convert the request into the format used, only BBB for now*/
775     sc->ata_request = request;
776
777     /* ATA/ATAPI IDENTIFY needs special treatment */
778     if (!(request->flags & ATA_R_ATAPI)) {
779         if (request->u.ata.command != ATA_ATAPI_IDENTIFY) {
780             device_printf(request->dev,"%s unsupported\n",ata_cmd2str(request));
781             request->result = EIO;
782             return ATA_OP_FINISHED;
783         }
784         request->flags |= ATA_R_ATAPI;
785         bzero(request->u.atapi.ccb, 16);
786         request->u.atapi.ccb[0] = ATAPI_INQUIRY;
787         request->u.atapi.ccb[4] =  255; //sizeof(struct atapi_inquiry);
788         request->data += 256;   /* arbitrary offset into ata_param */
789         request->bytecount = 255; //sizeof(struct atapi_inquiry);
790     }
791     return atausb_bbb_start(request);
792 }
793
794 int
795 ata_usbchannel_end_transaction(struct ata_request *request)
796 {
797     if (atausbdebug > 1)
798         device_printf(request->dev, "end_transaction %s\n",
799                       ata_cmd2str(request));
800     
801     /* XXX SOS convert the request from the format used, only BBB for now*/
802
803     /* ATA/ATAPI IDENTIFY needs special treatment */
804     if ((request->flags & ATA_R_ATAPI) &&
805         (request->u.atapi.ccb[0] == ATAPI_INQUIRY)) {
806         struct ata_device *atadev = device_get_softc(request->dev);
807         struct atapi_inquiry *inquiry = (struct atapi_inquiry *)request->data;
808         u_int16_t *ptr;
809
810         /* convert inquiry data into simple ata_param like format */
811         atadev->param.config = ATA_PROTO_ATAPI | ATA_PROTO_ATAPI_12;
812         atadev->param.config |= (inquiry->device_type & 0x1f) << 8;
813         bzero(atadev->param.model, sizeof(atadev->param.model));
814         strncpy(atadev->param.model, inquiry->vendor, 8);
815         strcpy(atadev->param.model, "  ");
816         strncpy(atadev->param.model, inquiry->product, 16);
817         ptr = (u_int16_t*)(atadev->param.model + sizeof(atadev->param.model));
818         while (--ptr >= (u_int16_t*)atadev->param.model)
819             *ptr = ntohs(*ptr);
820         strncpy(atadev->param.revision, inquiry->revision, 4);
821         ptr=(u_int16_t*)(atadev->param.revision+sizeof(atadev->param.revision));
822         while (--ptr >= (u_int16_t*)atadev->param.revision)
823             *ptr = ntohs(*ptr);
824         request->result = 0;
825     }
826     return ATA_OP_FINISHED;
827 }
828
829 static int
830 ata_usbchannel_probe(device_t dev)
831 {
832     struct ata_channel *ch = device_get_softc(dev);
833     device_t *children;
834     int count, i;
835     char buffer[32];
836
837     /* take care of green memory */
838     bzero(ch, sizeof(struct ata_channel));
839
840     /* find channel number on this controller */
841     device_get_children(device_get_parent(dev), &children, &count);
842     for (i = 0; i < count; i++) {
843         if (children[i] == dev)
844             ch->unit = i;
845     }
846     free(children, M_TEMP);
847
848     sprintf(buffer, "USB lun %d", ch->unit);
849     device_set_desc_copy(dev, buffer);
850
851     return 0;
852 }
853
854 static int
855 ata_usbchannel_attach(device_t dev)
856 {
857     struct ata_channel *ch = device_get_softc(dev);
858
859     /* initialize the softc basics */
860     ch->dev = dev;
861     ch->state = ATA_IDLE;
862     ch->hw.begin_transaction = ata_usbchannel_begin_transaction;
863     ch->hw.end_transaction = ata_usbchannel_end_transaction;
864     ch->hw.status = NULL;
865     ch->hw.command = NULL;
866     bzero(&ch->state_mtx, sizeof(struct mtx));
867     mtx_init(&ch->state_mtx, "ATA state lock", NULL, MTX_DEF);
868     bzero(&ch->queue_mtx, sizeof(struct mtx));
869     mtx_init(&ch->queue_mtx, "ATA queue lock", NULL, MTX_DEF);
870     TAILQ_INIT(&ch->ata_queue);
871
872     /* XXX SOS reset the controller HW, the channel and device(s) */
873     //ATA_RESET(dev);
874
875     /* probe and attach device on this channel */
876     ch->devices = ATA_ATAPI_MASTER;
877     if (!ata_delayed_attach)
878         ata_identify(dev);
879     return 0;
880 }
881
882 static int
883 ata_usbchannel_detach(device_t dev)
884 {
885     struct ata_channel *ch = device_get_softc(dev);
886     device_t *children;
887     int nchildren, i;
888
889     /* detach & delete all children */
890     if (!device_get_children(dev, &children, &nchildren)) {
891         for (i = 0; i < nchildren; i++)
892             if (children[i])
893                 device_delete_child(dev, children[i]);
894         free(children, M_TEMP);
895     }
896     mtx_destroy(&ch->state_mtx);
897     mtx_destroy(&ch->queue_mtx);
898     return 0;
899 }
900
901 static void
902 ata_usbchannel_setmode(device_t parent, device_t dev)
903 {
904     struct atausb_softc *sc = device_get_softc(GRANDPARENT(dev));
905     struct ata_device *atadev = device_get_softc(dev);
906     usbd_device_handle udev;
907
908     usbd_interface2device_handle(sc->iface, &udev);
909     if (usbd_get_speed(udev) == USB_SPEED_HIGH)
910         atadev->mode = ATA_USB2;
911     else
912         atadev->mode = ATA_USB1;
913 }
914
915 static int
916 ata_usbchannel_locking(device_t dev, int flags)
917 {
918     struct atausb_softc *sc = device_get_softc(device_get_parent(dev));
919     struct ata_channel *ch = device_get_softc(dev);
920     int res = -1;
921
922
923     mtx_lock(&sc->locked_mtx);
924     switch (flags) {
925     case ATA_LF_LOCK:
926         if (sc->locked_ch == NULL)
927             sc->locked_ch = ch;
928         if (sc->locked_ch != ch)
929             sc->restart_ch = ch;
930         break;
931
932     case ATA_LF_UNLOCK:
933         if (sc->locked_ch == ch) {
934             sc->locked_ch = NULL;
935             if (sc->restart_ch) {
936                 ch = sc->restart_ch;
937                 sc->restart_ch = NULL;
938                 mtx_unlock(&sc->locked_mtx);
939                 ata_start(ch->dev);
940                 return res;
941             }
942         }
943         break;
944
945     case ATA_LF_WHICH:
946         break;
947     }
948     if (sc->locked_ch)
949         res = sc->locked_ch->unit;
950     mtx_unlock(&sc->locked_mtx);
951     return res;
952 }
953
954 static device_method_t ata_usbchannel_methods[] = {
955     /* device interface */
956     DEVMETHOD(device_probe,         ata_usbchannel_probe),
957     DEVMETHOD(device_attach,        ata_usbchannel_attach),
958     DEVMETHOD(device_detach,        ata_usbchannel_detach),
959
960     /* ATA methods */
961     DEVMETHOD(ata_setmode,        ata_usbchannel_setmode),
962     DEVMETHOD(ata_locking,        ata_usbchannel_locking),
963     //DEVMETHOD(ata_reset,        ata_usbchannel_reset),
964
965     { 0, 0 }
966 };
967
968 static driver_t ata_usbchannel_driver = {
969     "ata",
970     ata_usbchannel_methods,
971     sizeof(struct ata_channel),
972 };
973
974 DRIVER_MODULE(ata, atausb, ata_usbchannel_driver, ata_devclass, 0, 0);
975 MODULE_DEPEND(atausb, ata, 1, 1, 1);