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