]> CyberLeo.Net >> Repos - FreeBSD/FreeBSD.git/blob - sys/dev/ata/ata-usb.c
This commit was generated by cvs2svn to compensate for changes in r157191,
[FreeBSD/FreeBSD.git] / sys / dev / ata / 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
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     USBBASEDEVICE       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_ptr_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->result = ENODEV;
687             request->error = ATA_SK_RESERVED;
688             sc->state = ATAUSB_S_IDLE;
689             ata_interrupt(device_get_softc(request->parent));
690             return;
691         }
692         else {
693             sc->state = ATAUSB_S_IDLE;
694             ata_interrupt(device_get_softc(request->parent));
695             return;
696         }
697         /* NOT REACHED */
698
699     case ATAUSB_S_BBB_RESET1:
700         if (err)
701             if (atausbdebug)
702                 device_printf(sc->dev,
703                               "BBB reset failure: %s\n", usbd_errstr(err));
704         atausb_clear_stall(sc, sc->bulkin, sc->bulkin_pipe,
705                            ATAUSB_S_BBB_RESET2,
706                            sc->transfer[ATAUSB_T_BBB_RESET2]);
707         return;
708
709     case ATAUSB_S_BBB_RESET2:
710         if (err)
711             if (atausbdebug)
712                 device_printf(sc->dev, "BBB bulkin clear stall failure: %s\n",
713                               usbd_errstr(err));
714         atausb_clear_stall(sc, sc->bulkout, sc->bulkout_pipe,
715                            ATAUSB_S_BBB_RESET3,
716                            sc->transfer[ATAUSB_T_BBB_RESET3]);
717         return;
718
719     case ATAUSB_S_BBB_RESET3:
720         if (err)
721             if (atausbdebug)
722                 device_printf(sc->dev, "BBB bulk-out clear stall failure: %s\n",
723                               usbd_errstr(err));
724         sc->state = ATAUSB_S_IDLE;
725         if (request) {
726             if (err)
727                 request->result = ENXIO;
728             else
729                 request->result = EIO;
730             ata_interrupt(device_get_softc(request->parent));
731         }
732         return;
733
734     default:
735         if (atausbdebug)
736             device_printf(sc->dev, "unknown state %d", sc->state);
737     }
738 }
739
740
741 /*
742  * ATA backend part
743  */
744 struct atapi_inquiry {
745     u_int8_t    device_type;
746     u_int8_t    device_modifier;
747     u_int8_t    version;
748     u_int8_t    response_format;
749     u_int8_t    length;
750     u_int8_t    reserved[2];
751     u_int8_t    flags;
752     u_int8_t    vendor[8];
753     u_int8_t    product[16];
754     u_int8_t    revision[4];
755     //u_int8_t    crap[60];
756 };
757
758 int
759 ata_usbchannel_begin_transaction(struct ata_request *request)
760 {
761     struct atausb_softc *sc = 
762         device_get_softc(device_get_parent(request->parent));
763
764     if (atausbdebug > 1)
765         device_printf(request->dev, "begin_transaction %s\n",
766                       ata_cmd2str(request));
767
768     /* sanity just in case */
769     if (sc->state != ATAUSB_S_IDLE) {
770         printf("begin is busy (%d)\n", sc->state);
771         request->result = EBUSY;
772         return ATA_OP_FINISHED;
773     }
774
775     /* XXX SOS convert the request into the format used, only BBB for now*/
776     sc->ata_request = request;
777
778     /* ATA/ATAPI IDENTIFY needs special treatment */
779     if (!(request->flags & ATA_R_ATAPI)) {
780         if (request->u.ata.command != ATA_ATAPI_IDENTIFY) {
781             device_printf(request->dev,"%s unsupported\n",ata_cmd2str(request));
782             request->result = EIO;
783             return ATA_OP_FINISHED;
784         }
785         request->flags |= ATA_R_ATAPI;
786         bzero(request->u.atapi.ccb, 16);
787         request->u.atapi.ccb[0] = ATAPI_INQUIRY;
788         request->u.atapi.ccb[4] =  255; //sizeof(struct atapi_inquiry);
789         request->data += 256;   /* arbitrary offset into ata_param */
790         request->bytecount = 255; //sizeof(struct atapi_inquiry);
791     }
792     return atausb_bbb_start(request);
793 }
794
795 int
796 ata_usbchannel_end_transaction(struct ata_request *request)
797 {
798     if (atausbdebug > 1)
799         device_printf(request->dev, "end_transaction %s\n",
800                       ata_cmd2str(request));
801     
802     /* XXX SOS convert the request from the format used, only BBB for now*/
803
804     /* ATA/ATAPI IDENTIFY needs special treatment */
805     if ((request->flags & ATA_R_ATAPI) &&
806         (request->u.atapi.ccb[0] == ATAPI_INQUIRY)) {
807         struct ata_device *atadev = device_get_softc(request->dev);
808         struct atapi_inquiry *inquiry = (struct atapi_inquiry *)request->data;
809         u_int16_t *ptr;
810
811         /* convert inquiry data into simple ata_param like format */
812         atadev->param.config = ATA_PROTO_ATAPI | ATA_PROTO_ATAPI_12;
813         atadev->param.config |= (inquiry->device_type & 0x1f) << 8;
814         bzero(atadev->param.model, sizeof(atadev->param.model));
815         strncpy(atadev->param.model, inquiry->vendor, 8);
816         strcpy(atadev->param.model, "  ");
817         strncpy(atadev->param.model, inquiry->product, 16);
818         ptr = (u_int16_t*)(atadev->param.model + sizeof(atadev->param.model));
819         while (--ptr >= (u_int16_t*)atadev->param.model)
820             *ptr = ntohs(*ptr);
821         strncpy(atadev->param.revision, inquiry->revision, 4);
822         ptr=(u_int16_t*)(atadev->param.revision+sizeof(atadev->param.revision));
823         while (--ptr >= (u_int16_t*)atadev->param.revision)
824             *ptr = ntohs(*ptr);
825         request->result = 0;
826     }
827     if ((request->flags & ATA_R_ATAPI) &&
828         (request->u.atapi.ccb[0] == ATAPI_REQUEST_SENSE))
829         request->u.atapi.sense_key = request->u.atapi.sense_data.sense_key << 4;
830     return ATA_OP_FINISHED;
831 }
832
833 static int
834 ata_usbchannel_probe(device_t dev)
835 {
836     struct ata_channel *ch = device_get_softc(dev);
837     device_t *children;
838     int count, i;
839     char buffer[32];
840
841     /* take care of green memory */
842     bzero(ch, sizeof(struct ata_channel));
843
844     /* find channel number on this controller */
845     device_get_children(device_get_parent(dev), &children, &count);
846     for (i = 0; i < count; i++) {
847         if (children[i] == dev)
848             ch->unit = i;
849     }
850     free(children, M_TEMP);
851
852     sprintf(buffer, "USB lun %d", ch->unit);
853     device_set_desc_copy(dev, buffer);
854
855     return 0;
856 }
857
858 static int
859 ata_usbchannel_attach(device_t dev)
860 {
861     struct ata_channel *ch = device_get_softc(dev);
862
863     /* initialize the softc basics */
864     ch->dev = dev;
865     ch->state = ATA_IDLE;
866     ch->hw.begin_transaction = ata_usbchannel_begin_transaction;
867     ch->hw.end_transaction = ata_usbchannel_end_transaction;
868     ch->hw.status = NULL;
869     ch->hw.command = NULL;
870     bzero(&ch->state_mtx, sizeof(struct mtx));
871     mtx_init(&ch->state_mtx, "ATA state lock", NULL, MTX_DEF);
872     bzero(&ch->queue_mtx, sizeof(struct mtx));
873     mtx_init(&ch->queue_mtx, "ATA queue lock", NULL, MTX_DEF);
874     TAILQ_INIT(&ch->ata_queue);
875
876     /* XXX SOS reset the controller HW, the channel and device(s) */
877     //ATA_RESET(dev);
878
879     /* probe and attach device on this channel */
880     ch->devices = ATA_ATAPI_MASTER;
881     if (!ata_delayed_attach)
882         ata_identify(dev);
883     return 0;
884 }
885
886 static int
887 ata_usbchannel_detach(device_t dev)
888 {
889     struct ata_channel *ch = device_get_softc(dev);
890     device_t *children;
891     int nchildren, i;
892
893     /* detach & delete all children */
894     if (!device_get_children(dev, &children, &nchildren)) {
895         for (i = 0; i < nchildren; i++)
896             if (children[i])
897                 device_delete_child(dev, children[i]);
898         free(children, M_TEMP);
899     }
900     mtx_destroy(&ch->state_mtx);
901     mtx_destroy(&ch->queue_mtx);
902     return 0;
903 }
904
905 static void
906 ata_usbchannel_setmode(device_t parent, device_t dev)
907 {
908     struct atausb_softc *sc = device_get_softc(GRANDPARENT(dev));
909     struct ata_device *atadev = device_get_softc(dev);
910     usbd_device_handle udev;
911
912     usbd_interface2device_handle(sc->iface, &udev);
913     if (usbd_get_speed(udev) == USB_SPEED_HIGH)
914         atadev->mode = ATA_USB2;
915     else
916         atadev->mode = ATA_USB1;
917 }
918
919 static int
920 ata_usbchannel_locking(device_t dev, int flags)
921 {
922     struct atausb_softc *sc = device_get_softc(device_get_parent(dev));
923     struct ata_channel *ch = device_get_softc(dev);
924     int res = -1;
925
926
927     mtx_lock(&sc->locked_mtx);
928     switch (flags) {
929     case ATA_LF_LOCK:
930         if (sc->locked_ch == NULL)
931             sc->locked_ch = ch;
932         if (sc->locked_ch != ch)
933             sc->restart_ch = ch;
934         break;
935
936     case ATA_LF_UNLOCK:
937         if (sc->locked_ch == ch) {
938             sc->locked_ch = NULL;
939             if (sc->restart_ch) {
940                 ch = sc->restart_ch;
941                 sc->restart_ch = NULL;
942                 mtx_unlock(&sc->locked_mtx);
943                 ata_start(ch->dev);
944                 return res;
945             }
946         }
947         break;
948
949     case ATA_LF_WHICH:
950         break;
951     }
952     if (sc->locked_ch)
953         res = sc->locked_ch->unit;
954     mtx_unlock(&sc->locked_mtx);
955     return res;
956 }
957
958 static device_method_t ata_usbchannel_methods[] = {
959     /* device interface */
960     DEVMETHOD(device_probe,         ata_usbchannel_probe),
961     DEVMETHOD(device_attach,        ata_usbchannel_attach),
962     DEVMETHOD(device_detach,        ata_usbchannel_detach),
963
964     /* ATA methods */
965     DEVMETHOD(ata_setmode,        ata_usbchannel_setmode),
966     DEVMETHOD(ata_locking,        ata_usbchannel_locking),
967     //DEVMETHOD(ata_reset,        ata_usbchannel_reset),
968
969     { 0, 0 }
970 };
971
972 static driver_t ata_usbchannel_driver = {
973     "ata",
974     ata_usbchannel_methods,
975     sizeof(struct ata_channel),
976 };
977
978 DRIVER_MODULE(ata, atausb, ata_usbchannel_driver, ata_devclass, 0, 0);
979 MODULE_DEPEND(atausb, ata, 1, 1, 1);