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