xref: /openbmc/qemu/hw/usb/dev-uas.c (revision a42e9c41)
1 /*
2  * UAS (USB Attached SCSI) emulation
3  *
4  * Copyright Red Hat, Inc. 2012
5  *
6  * Author: Gerd Hoffmann <kraxel@redhat.com>
7  *
8  * This work is licensed under the terms of the GNU GPL, version 2 or later.
9  * See the COPYING file in the top-level directory.
10  */
11 
12 #include "qemu-common.h"
13 #include "qemu/option.h"
14 #include "qemu/config-file.h"
15 #include "trace.h"
16 
17 #include "hw/usb.h"
18 #include "hw/usb/desc.h"
19 #include "hw/scsi/scsi.h"
20 #include "block/scsi.h"
21 
22 /* --------------------------------------------------------------------- */
23 
24 #define UAS_UI_COMMAND              0x01
25 #define UAS_UI_SENSE                0x03
26 #define UAS_UI_RESPONSE             0x04
27 #define UAS_UI_TASK_MGMT            0x05
28 #define UAS_UI_READ_READY           0x06
29 #define UAS_UI_WRITE_READY          0x07
30 
31 #define UAS_RC_TMF_COMPLETE         0x00
32 #define UAS_RC_INVALID_INFO_UNIT    0x02
33 #define UAS_RC_TMF_NOT_SUPPORTED    0x04
34 #define UAS_RC_TMF_FAILED           0x05
35 #define UAS_RC_TMF_SUCCEEDED        0x08
36 #define UAS_RC_INCORRECT_LUN        0x09
37 #define UAS_RC_OVERLAPPED_TAG       0x0a
38 
39 #define UAS_TMF_ABORT_TASK          0x01
40 #define UAS_TMF_ABORT_TASK_SET      0x02
41 #define UAS_TMF_CLEAR_TASK_SET      0x04
42 #define UAS_TMF_LOGICAL_UNIT_RESET  0x08
43 #define UAS_TMF_I_T_NEXUS_RESET     0x10
44 #define UAS_TMF_CLEAR_ACA           0x40
45 #define UAS_TMF_QUERY_TASK          0x80
46 #define UAS_TMF_QUERY_TASK_SET      0x81
47 #define UAS_TMF_QUERY_ASYNC_EVENT   0x82
48 
49 #define UAS_PIPE_ID_COMMAND         0x01
50 #define UAS_PIPE_ID_STATUS          0x02
51 #define UAS_PIPE_ID_DATA_IN         0x03
52 #define UAS_PIPE_ID_DATA_OUT        0x04
53 
54 typedef struct {
55     uint8_t    id;
56     uint8_t    reserved;
57     uint16_t   tag;
58 } QEMU_PACKED  uas_ui_header;
59 
60 typedef struct {
61     uint8_t    prio_taskattr;   /* 6:3 priority, 2:0 task attribute   */
62     uint8_t    reserved_1;
63     uint8_t    add_cdb_length;  /* 7:2 additional adb length (dwords) */
64     uint8_t    reserved_2;
65     uint64_t   lun;
66     uint8_t    cdb[16];
67     uint8_t    add_cdb[];
68 } QEMU_PACKED  uas_ui_command;
69 
70 typedef struct {
71     uint16_t   status_qualifier;
72     uint8_t    status;
73     uint8_t    reserved[7];
74     uint16_t   sense_length;
75     uint8_t    sense_data[18];
76 } QEMU_PACKED  uas_ui_sense;
77 
78 typedef struct {
79     uint16_t   add_response_info;
80     uint8_t    response_code;
81 } QEMU_PACKED  uas_ui_response;
82 
83 typedef struct {
84     uint8_t    function;
85     uint8_t    reserved;
86     uint16_t   task_tag;
87     uint64_t   lun;
88 } QEMU_PACKED  uas_ui_task_mgmt;
89 
90 typedef struct {
91     uas_ui_header  hdr;
92     union {
93         uas_ui_command   command;
94         uas_ui_sense     sense;
95         uas_ui_task_mgmt task;
96         uas_ui_response  response;
97     };
98 } QEMU_PACKED  uas_ui;
99 
100 /* --------------------------------------------------------------------- */
101 
102 #define UAS_STREAM_BM_ATTR  4
103 #define UAS_MAX_STREAMS     (1 << UAS_STREAM_BM_ATTR)
104 
105 typedef struct UASDevice UASDevice;
106 typedef struct UASRequest UASRequest;
107 typedef struct UASStatus UASStatus;
108 
109 struct UASDevice {
110     USBDevice                 dev;
111     SCSIBus                   bus;
112     QEMUBH                    *status_bh;
113     QTAILQ_HEAD(, UASStatus)  results;
114     QTAILQ_HEAD(, UASRequest) requests;
115 
116     /* properties */
117     uint32_t                  requestlog;
118 
119     /* usb 2.0 only */
120     USBPacket                 *status2;
121     UASRequest                *datain2;
122     UASRequest                *dataout2;
123 
124     /* usb 3.0 only */
125     USBPacket                 *data3[UAS_MAX_STREAMS];
126     USBPacket                 *status3[UAS_MAX_STREAMS];
127 };
128 
129 struct UASRequest {
130     uint16_t     tag;
131     uint64_t     lun;
132     UASDevice    *uas;
133     SCSIDevice   *dev;
134     SCSIRequest  *req;
135     USBPacket    *data;
136     bool         data_async;
137     bool         active;
138     bool         complete;
139     uint32_t     buf_off;
140     uint32_t     buf_size;
141     uint32_t     data_off;
142     uint32_t     data_size;
143     QTAILQ_ENTRY(UASRequest)  next;
144 };
145 
146 struct UASStatus {
147     uint32_t                  stream;
148     uas_ui                    status;
149     uint32_t                  length;
150     QTAILQ_ENTRY(UASStatus)   next;
151 };
152 
153 /* --------------------------------------------------------------------- */
154 
155 enum {
156     STR_MANUFACTURER = 1,
157     STR_PRODUCT,
158     STR_SERIALNUMBER,
159     STR_CONFIG_HIGH,
160     STR_CONFIG_SUPER,
161 };
162 
163 static const USBDescStrings desc_strings = {
164     [STR_MANUFACTURER] = "QEMU",
165     [STR_PRODUCT]      = "USB Attached SCSI HBA",
166     [STR_SERIALNUMBER] = "27842",
167     [STR_CONFIG_HIGH]  = "High speed config (usb 2.0)",
168     [STR_CONFIG_SUPER] = "Super speed config (usb 3.0)",
169 };
170 
171 static const USBDescIface desc_iface_high = {
172     .bInterfaceNumber              = 0,
173     .bNumEndpoints                 = 4,
174     .bInterfaceClass               = USB_CLASS_MASS_STORAGE,
175     .bInterfaceSubClass            = 0x06, /* SCSI */
176     .bInterfaceProtocol            = 0x62, /* UAS  */
177     .eps = (USBDescEndpoint[]) {
178         {
179             .bEndpointAddress      = USB_DIR_OUT | UAS_PIPE_ID_COMMAND,
180             .bmAttributes          = USB_ENDPOINT_XFER_BULK,
181             .wMaxPacketSize        = 512,
182             .extra = (uint8_t[]) {
183                 0x04,  /*  u8  bLength */
184                 0x24,  /*  u8  bDescriptorType */
185                 UAS_PIPE_ID_COMMAND,
186                 0x00,  /*  u8  bReserved */
187             },
188         },{
189             .bEndpointAddress      = USB_DIR_IN | UAS_PIPE_ID_STATUS,
190             .bmAttributes          = USB_ENDPOINT_XFER_BULK,
191             .wMaxPacketSize        = 512,
192             .extra = (uint8_t[]) {
193                 0x04,  /*  u8  bLength */
194                 0x24,  /*  u8  bDescriptorType */
195                 UAS_PIPE_ID_STATUS,
196                 0x00,  /*  u8  bReserved */
197             },
198         },{
199             .bEndpointAddress      = USB_DIR_IN | UAS_PIPE_ID_DATA_IN,
200             .bmAttributes          = USB_ENDPOINT_XFER_BULK,
201             .wMaxPacketSize        = 512,
202             .extra = (uint8_t[]) {
203                 0x04,  /*  u8  bLength */
204                 0x24,  /*  u8  bDescriptorType */
205                 UAS_PIPE_ID_DATA_IN,
206                 0x00,  /*  u8  bReserved */
207             },
208         },{
209             .bEndpointAddress      = USB_DIR_OUT | UAS_PIPE_ID_DATA_OUT,
210             .bmAttributes          = USB_ENDPOINT_XFER_BULK,
211             .wMaxPacketSize        = 512,
212             .extra = (uint8_t[]) {
213                 0x04,  /*  u8  bLength */
214                 0x24,  /*  u8  bDescriptorType */
215                 UAS_PIPE_ID_DATA_OUT,
216                 0x00,  /*  u8  bReserved */
217             },
218         },
219     }
220 };
221 
222 static const USBDescIface desc_iface_super = {
223     .bInterfaceNumber              = 0,
224     .bNumEndpoints                 = 4,
225     .bInterfaceClass               = USB_CLASS_MASS_STORAGE,
226     .bInterfaceSubClass            = 0x06, /* SCSI */
227     .bInterfaceProtocol            = 0x62, /* UAS  */
228     .eps = (USBDescEndpoint[]) {
229         {
230             .bEndpointAddress      = USB_DIR_OUT | UAS_PIPE_ID_COMMAND,
231             .bmAttributes          = USB_ENDPOINT_XFER_BULK,
232             .wMaxPacketSize        = 1024,
233             .bMaxBurst             = 15,
234             .extra = (uint8_t[]) {
235                 0x04,  /*  u8  bLength */
236                 0x24,  /*  u8  bDescriptorType */
237                 UAS_PIPE_ID_COMMAND,
238                 0x00,  /*  u8  bReserved */
239             },
240         },{
241             .bEndpointAddress      = USB_DIR_IN | UAS_PIPE_ID_STATUS,
242             .bmAttributes          = USB_ENDPOINT_XFER_BULK,
243             .wMaxPacketSize        = 1024,
244             .bMaxBurst             = 15,
245             .bmAttributes_super    = UAS_STREAM_BM_ATTR,
246             .extra = (uint8_t[]) {
247                 0x04,  /*  u8  bLength */
248                 0x24,  /*  u8  bDescriptorType */
249                 UAS_PIPE_ID_STATUS,
250                 0x00,  /*  u8  bReserved */
251             },
252         },{
253             .bEndpointAddress      = USB_DIR_IN | UAS_PIPE_ID_DATA_IN,
254             .bmAttributes          = USB_ENDPOINT_XFER_BULK,
255             .wMaxPacketSize        = 1024,
256             .bMaxBurst             = 15,
257             .bmAttributes_super    = UAS_STREAM_BM_ATTR,
258             .extra = (uint8_t[]) {
259                 0x04,  /*  u8  bLength */
260                 0x24,  /*  u8  bDescriptorType */
261                 UAS_PIPE_ID_DATA_IN,
262                 0x00,  /*  u8  bReserved */
263             },
264         },{
265             .bEndpointAddress      = USB_DIR_OUT | UAS_PIPE_ID_DATA_OUT,
266             .bmAttributes          = USB_ENDPOINT_XFER_BULK,
267             .wMaxPacketSize        = 1024,
268             .bMaxBurst             = 15,
269             .bmAttributes_super    = UAS_STREAM_BM_ATTR,
270             .extra = (uint8_t[]) {
271                 0x04,  /*  u8  bLength */
272                 0x24,  /*  u8  bDescriptorType */
273                 UAS_PIPE_ID_DATA_OUT,
274                 0x00,  /*  u8  bReserved */
275             },
276         },
277     }
278 };
279 
280 static const USBDescDevice desc_device_high = {
281     .bcdUSB                        = 0x0200,
282     .bMaxPacketSize0               = 64,
283     .bNumConfigurations            = 1,
284     .confs = (USBDescConfig[]) {
285         {
286             .bNumInterfaces        = 1,
287             .bConfigurationValue   = 1,
288             .iConfiguration        = STR_CONFIG_HIGH,
289             .bmAttributes          = 0xc0,
290             .nif = 1,
291             .ifs = &desc_iface_high,
292         },
293     },
294 };
295 
296 static const USBDescDevice desc_device_super = {
297     .bcdUSB                        = 0x0300,
298     .bMaxPacketSize0               = 64,
299     .bNumConfigurations            = 1,
300     .confs = (USBDescConfig[]) {
301         {
302             .bNumInterfaces        = 1,
303             .bConfigurationValue   = 1,
304             .iConfiguration        = STR_CONFIG_SUPER,
305             .bmAttributes          = 0xc0,
306             .nif = 1,
307             .ifs = &desc_iface_super,
308         },
309     },
310 };
311 
312 static const USBDesc desc = {
313     .id = {
314         .idVendor          = 0x46f4, /* CRC16() of "QEMU" */
315         .idProduct         = 0x0003,
316         .bcdDevice         = 0,
317         .iManufacturer     = STR_MANUFACTURER,
318         .iProduct          = STR_PRODUCT,
319         .iSerialNumber     = STR_SERIALNUMBER,
320     },
321     .high  = &desc_device_high,
322     .super = &desc_device_super,
323     .str   = desc_strings,
324 };
325 
326 /* --------------------------------------------------------------------- */
327 
328 static bool uas_using_streams(UASDevice *uas)
329 {
330     return uas->dev.speed == USB_SPEED_SUPER;
331 }
332 
333 /* --------------------------------------------------------------------- */
334 
335 static UASStatus *usb_uas_alloc_status(UASDevice *uas, uint8_t id, uint16_t tag)
336 {
337     UASStatus *st = g_new0(UASStatus, 1);
338 
339     st->status.hdr.id = id;
340     st->status.hdr.tag = cpu_to_be16(tag);
341     st->length = sizeof(uas_ui_header);
342     if (uas_using_streams(uas)) {
343         st->stream = tag;
344     }
345     return st;
346 }
347 
348 static void usb_uas_send_status_bh(void *opaque)
349 {
350     UASDevice *uas = opaque;
351     UASStatus *st;
352     USBPacket *p;
353 
354     while ((st = QTAILQ_FIRST(&uas->results)) != NULL) {
355         if (uas_using_streams(uas)) {
356             p = uas->status3[st->stream];
357             uas->status3[st->stream] = NULL;
358         } else {
359             p = uas->status2;
360             uas->status2 = NULL;
361         }
362         if (p == NULL) {
363             break;
364         }
365 
366         usb_packet_copy(p, &st->status, st->length);
367         QTAILQ_REMOVE(&uas->results, st, next);
368         g_free(st);
369 
370         p->status = USB_RET_SUCCESS; /* Clear previous ASYNC status */
371         usb_packet_complete(&uas->dev, p);
372     }
373 }
374 
375 static void usb_uas_queue_status(UASDevice *uas, UASStatus *st, int length)
376 {
377     USBPacket *p = uas_using_streams(uas) ?
378         uas->status3[st->stream] : uas->status2;
379 
380     st->length += length;
381     QTAILQ_INSERT_TAIL(&uas->results, st, next);
382     if (p) {
383         /*
384          * Just schedule bh make sure any in-flight data transaction
385          * is finished before completing (sending) the status packet.
386          */
387         qemu_bh_schedule(uas->status_bh);
388     } else {
389         USBEndpoint *ep = usb_ep_get(&uas->dev, USB_TOKEN_IN,
390                                      UAS_PIPE_ID_STATUS);
391         usb_wakeup(ep, st->stream);
392     }
393 }
394 
395 static void usb_uas_queue_response(UASDevice *uas, uint16_t tag,
396                                    uint8_t code, uint16_t add_info)
397 {
398     UASStatus *st = usb_uas_alloc_status(uas, UAS_UI_RESPONSE, tag);
399 
400     trace_usb_uas_response(uas->dev.addr, tag, code);
401     st->status.response.response_code = code;
402     st->status.response.add_response_info = cpu_to_be16(add_info);
403     usb_uas_queue_status(uas, st, sizeof(uas_ui_response));
404 }
405 
406 static void usb_uas_queue_sense(UASRequest *req, uint8_t status)
407 {
408     UASStatus *st = usb_uas_alloc_status(req->uas, UAS_UI_SENSE, req->tag);
409     int len, slen = 0;
410 
411     trace_usb_uas_sense(req->uas->dev.addr, req->tag, status);
412     st->status.sense.status = status;
413     st->status.sense.status_qualifier = cpu_to_be16(0);
414     if (status != GOOD) {
415         slen = scsi_req_get_sense(req->req, st->status.sense.sense_data,
416                                   sizeof(st->status.sense.sense_data));
417         st->status.sense.sense_length = cpu_to_be16(slen);
418     }
419     len = sizeof(uas_ui_sense) - sizeof(st->status.sense.sense_data) + slen;
420     usb_uas_queue_status(req->uas, st, len);
421 }
422 
423 static void usb_uas_queue_read_ready(UASRequest *req)
424 {
425     UASStatus *st = usb_uas_alloc_status(req->uas, UAS_UI_READ_READY,
426                                          req->tag);
427 
428     trace_usb_uas_read_ready(req->uas->dev.addr, req->tag);
429     usb_uas_queue_status(req->uas, st, 0);
430 }
431 
432 static void usb_uas_queue_write_ready(UASRequest *req)
433 {
434     UASStatus *st = usb_uas_alloc_status(req->uas, UAS_UI_WRITE_READY,
435                                          req->tag);
436 
437     trace_usb_uas_write_ready(req->uas->dev.addr, req->tag);
438     usb_uas_queue_status(req->uas, st, 0);
439 }
440 
441 /* --------------------------------------------------------------------- */
442 
443 static int usb_uas_get_lun(uint64_t lun64)
444 {
445     return (lun64 >> 48) & 0xff;
446 }
447 
448 static SCSIDevice *usb_uas_get_dev(UASDevice *uas, uint64_t lun64)
449 {
450     if ((lun64 >> 56) != 0x00) {
451         return NULL;
452     }
453     return scsi_device_find(&uas->bus, 0, 0, usb_uas_get_lun(lun64));
454 }
455 
456 static void usb_uas_complete_data_packet(UASRequest *req)
457 {
458     USBPacket *p;
459 
460     if (!req->data_async) {
461         return;
462     }
463     p = req->data;
464     req->data = NULL;
465     req->data_async = false;
466     p->status = USB_RET_SUCCESS; /* Clear previous ASYNC status */
467     usb_packet_complete(&req->uas->dev, p);
468 }
469 
470 static void usb_uas_copy_data(UASRequest *req)
471 {
472     uint32_t length;
473 
474     length = MIN(req->buf_size - req->buf_off,
475                  req->data->iov.size - req->data->actual_length);
476     trace_usb_uas_xfer_data(req->uas->dev.addr, req->tag, length,
477                             req->data->actual_length, req->data->iov.size,
478                             req->buf_off, req->buf_size);
479     usb_packet_copy(req->data, scsi_req_get_buf(req->req) + req->buf_off,
480                     length);
481     req->buf_off += length;
482     req->data_off += length;
483 
484     if (req->data->actual_length == req->data->iov.size) {
485         usb_uas_complete_data_packet(req);
486     }
487     if (req->buf_size && req->buf_off == req->buf_size) {
488         req->buf_off = 0;
489         req->buf_size = 0;
490         scsi_req_continue(req->req);
491     }
492 }
493 
494 static void usb_uas_start_next_transfer(UASDevice *uas)
495 {
496     UASRequest *req;
497 
498     if (uas_using_streams(uas)) {
499         return;
500     }
501 
502     QTAILQ_FOREACH(req, &uas->requests, next) {
503         if (req->active || req->complete) {
504             continue;
505         }
506         if (req->req->cmd.mode == SCSI_XFER_FROM_DEV && uas->datain2 == NULL) {
507             uas->datain2 = req;
508             usb_uas_queue_read_ready(req);
509             req->active = true;
510             return;
511         }
512         if (req->req->cmd.mode == SCSI_XFER_TO_DEV && uas->dataout2 == NULL) {
513             uas->dataout2 = req;
514             usb_uas_queue_write_ready(req);
515             req->active = true;
516             return;
517         }
518     }
519 }
520 
521 static UASRequest *usb_uas_alloc_request(UASDevice *uas, uas_ui *ui)
522 {
523     UASRequest *req;
524 
525     req = g_new0(UASRequest, 1);
526     req->uas = uas;
527     req->tag = be16_to_cpu(ui->hdr.tag);
528     req->lun = be64_to_cpu(ui->command.lun);
529     req->dev = usb_uas_get_dev(req->uas, req->lun);
530     return req;
531 }
532 
533 static void usb_uas_scsi_free_request(SCSIBus *bus, void *priv)
534 {
535     UASRequest *req = priv;
536     UASDevice *uas = req->uas;
537 
538     if (req == uas->datain2) {
539         uas->datain2 = NULL;
540     }
541     if (req == uas->dataout2) {
542         uas->dataout2 = NULL;
543     }
544     QTAILQ_REMOVE(&uas->requests, req, next);
545     g_free(req);
546     usb_uas_start_next_transfer(uas);
547 }
548 
549 static UASRequest *usb_uas_find_request(UASDevice *uas, uint16_t tag)
550 {
551     UASRequest *req;
552 
553     QTAILQ_FOREACH(req, &uas->requests, next) {
554         if (req->tag == tag) {
555             return req;
556         }
557     }
558     return NULL;
559 }
560 
561 static void usb_uas_scsi_transfer_data(SCSIRequest *r, uint32_t len)
562 {
563     UASRequest *req = r->hba_private;
564 
565     trace_usb_uas_scsi_data(req->uas->dev.addr, req->tag, len);
566     req->buf_off = 0;
567     req->buf_size = len;
568     if (req->data) {
569         usb_uas_copy_data(req);
570     } else {
571         usb_uas_start_next_transfer(req->uas);
572     }
573 }
574 
575 static void usb_uas_scsi_command_complete(SCSIRequest *r,
576                                           uint32_t status, size_t resid)
577 {
578     UASRequest *req = r->hba_private;
579 
580     trace_usb_uas_scsi_complete(req->uas->dev.addr, req->tag, status, resid);
581     req->complete = true;
582     if (req->data) {
583         usb_uas_complete_data_packet(req);
584     }
585     usb_uas_queue_sense(req, status);
586     scsi_req_unref(req->req);
587 }
588 
589 static void usb_uas_scsi_request_cancelled(SCSIRequest *r)
590 {
591     UASRequest *req = r->hba_private;
592 
593     /* FIXME: queue notification to status pipe? */
594     scsi_req_unref(req->req);
595 }
596 
597 static const struct SCSIBusInfo usb_uas_scsi_info = {
598     .tcq = true,
599     .max_target = 0,
600     .max_lun = 255,
601 
602     .transfer_data = usb_uas_scsi_transfer_data,
603     .complete = usb_uas_scsi_command_complete,
604     .cancel = usb_uas_scsi_request_cancelled,
605     .free_request = usb_uas_scsi_free_request,
606 };
607 
608 /* --------------------------------------------------------------------- */
609 
610 static void usb_uas_handle_reset(USBDevice *dev)
611 {
612     UASDevice *uas = DO_UPCAST(UASDevice, dev, dev);
613     UASRequest *req, *nreq;
614     UASStatus *st, *nst;
615 
616     trace_usb_uas_reset(dev->addr);
617     QTAILQ_FOREACH_SAFE(req, &uas->requests, next, nreq) {
618         scsi_req_cancel(req->req);
619     }
620     QTAILQ_FOREACH_SAFE(st, &uas->results, next, nst) {
621         QTAILQ_REMOVE(&uas->results, st, next);
622         g_free(st);
623     }
624 }
625 
626 static void usb_uas_handle_control(USBDevice *dev, USBPacket *p,
627                int request, int value, int index, int length, uint8_t *data)
628 {
629     int ret;
630 
631     ret = usb_desc_handle_control(dev, p, request, value, index, length, data);
632     if (ret >= 0) {
633         return;
634     }
635     fprintf(stderr, "%s: unhandled control request\n", __func__);
636     p->status = USB_RET_STALL;
637 }
638 
639 static void usb_uas_cancel_io(USBDevice *dev, USBPacket *p)
640 {
641     UASDevice *uas = DO_UPCAST(UASDevice, dev, dev);
642     UASRequest *req, *nreq;
643     int i;
644 
645     if (uas->status2 == p) {
646         uas->status2 = NULL;
647         qemu_bh_cancel(uas->status_bh);
648         return;
649     }
650     if (uas_using_streams(uas)) {
651         for (i = 0; i < UAS_MAX_STREAMS; i++) {
652             if (uas->status3[i] == p) {
653                 uas->status3[i] = NULL;
654                 return;
655             }
656             if (uas->data3[i] == p) {
657                 uas->data3[i] = NULL;
658                 return;
659             }
660         }
661     }
662     QTAILQ_FOREACH_SAFE(req, &uas->requests, next, nreq) {
663         if (req->data == p) {
664             req->data = NULL;
665             return;
666         }
667     }
668     assert(!"canceled usb packet not found");
669 }
670 
671 static void usb_uas_command(UASDevice *uas, uas_ui *ui)
672 {
673     UASRequest *req;
674     uint32_t len;
675 
676     req = usb_uas_find_request(uas, be16_to_cpu(ui->hdr.tag));
677     if (req) {
678         goto overlapped_tag;
679     }
680     req = usb_uas_alloc_request(uas, ui);
681     if (req->dev == NULL) {
682         goto bad_target;
683     }
684 
685     trace_usb_uas_command(uas->dev.addr, req->tag,
686                           usb_uas_get_lun(req->lun),
687                           req->lun >> 32, req->lun & 0xffffffff);
688     QTAILQ_INSERT_TAIL(&uas->requests, req, next);
689     if (uas_using_streams(uas) && uas->data3[req->tag] != NULL) {
690         req->data = uas->data3[req->tag];
691         req->data_async = true;
692         uas->data3[req->tag] = NULL;
693     }
694 
695     req->req = scsi_req_new(req->dev, req->tag,
696                             usb_uas_get_lun(req->lun),
697                             ui->command.cdb, req);
698     if (uas->requestlog) {
699         scsi_req_print(req->req);
700     }
701     len = scsi_req_enqueue(req->req);
702     if (len) {
703         req->data_size = len;
704         scsi_req_continue(req->req);
705     }
706     return;
707 
708 overlapped_tag:
709     usb_uas_queue_response(uas, req->tag, UAS_RC_OVERLAPPED_TAG, 0);
710     return;
711 
712 bad_target:
713     /*
714      * FIXME: Seems to upset linux, is this wrong?
715      * NOTE: Happens only with no scsi devices at the bus, not sure
716      *       this is a valid UAS setup in the first place.
717      */
718     usb_uas_queue_response(uas, req->tag, UAS_RC_INVALID_INFO_UNIT, 0);
719     g_free(req);
720 }
721 
722 static void usb_uas_task(UASDevice *uas, uas_ui *ui)
723 {
724     uint16_t tag = be16_to_cpu(ui->hdr.tag);
725     uint64_t lun64 = be64_to_cpu(ui->task.lun);
726     SCSIDevice *dev = usb_uas_get_dev(uas, lun64);
727     int lun = usb_uas_get_lun(lun64);
728     UASRequest *req;
729     uint16_t task_tag;
730 
731     req = usb_uas_find_request(uas, be16_to_cpu(ui->hdr.tag));
732     if (req) {
733         goto overlapped_tag;
734     }
735 
736     switch (ui->task.function) {
737     case UAS_TMF_ABORT_TASK:
738         task_tag = be16_to_cpu(ui->task.task_tag);
739         trace_usb_uas_tmf_abort_task(uas->dev.addr, tag, task_tag);
740         if (dev == NULL) {
741             goto bad_target;
742         }
743         if (dev->lun != lun) {
744             goto incorrect_lun;
745         }
746         req = usb_uas_find_request(uas, task_tag);
747         if (req && req->dev == dev) {
748             scsi_req_cancel(req->req);
749         }
750         usb_uas_queue_response(uas, tag, UAS_RC_TMF_COMPLETE, 0);
751         break;
752 
753     case UAS_TMF_LOGICAL_UNIT_RESET:
754         trace_usb_uas_tmf_logical_unit_reset(uas->dev.addr, tag, lun);
755         if (dev == NULL) {
756             goto bad_target;
757         }
758         if (dev->lun != lun) {
759             goto incorrect_lun;
760         }
761         qdev_reset_all(&dev->qdev);
762         usb_uas_queue_response(uas, tag, UAS_RC_TMF_COMPLETE, 0);
763         break;
764 
765     default:
766         trace_usb_uas_tmf_unsupported(uas->dev.addr, tag, ui->task.function);
767         usb_uas_queue_response(uas, tag, UAS_RC_TMF_NOT_SUPPORTED, 0);
768         break;
769     }
770     return;
771 
772 overlapped_tag:
773     usb_uas_queue_response(uas, req->tag, UAS_RC_OVERLAPPED_TAG, 0);
774     return;
775 
776 bad_target:
777     /* FIXME: correct?  [see long comment in usb_uas_command()] */
778     usb_uas_queue_response(uas, tag, UAS_RC_INVALID_INFO_UNIT, 0);
779     return;
780 
781 incorrect_lun:
782     usb_uas_queue_response(uas, tag, UAS_RC_INCORRECT_LUN, 0);
783 }
784 
785 static void usb_uas_handle_data(USBDevice *dev, USBPacket *p)
786 {
787     UASDevice *uas = DO_UPCAST(UASDevice, dev, dev);
788     uas_ui ui;
789     UASStatus *st;
790     UASRequest *req;
791     int length;
792 
793     switch (p->ep->nr) {
794     case UAS_PIPE_ID_COMMAND:
795         length = MIN(sizeof(ui), p->iov.size);
796         usb_packet_copy(p, &ui, length);
797         switch (ui.hdr.id) {
798         case UAS_UI_COMMAND:
799             usb_uas_command(uas, &ui);
800             break;
801         case UAS_UI_TASK_MGMT:
802             usb_uas_task(uas, &ui);
803             break;
804         default:
805             fprintf(stderr, "%s: unknown command ui: id 0x%x\n",
806                     __func__, ui.hdr.id);
807             p->status = USB_RET_STALL;
808             break;
809         }
810         break;
811     case UAS_PIPE_ID_STATUS:
812         if (p->stream) {
813             QTAILQ_FOREACH(st, &uas->results, next) {
814                 if (st->stream == p->stream) {
815                     break;
816                 }
817             }
818             if (st == NULL) {
819                 assert(uas->status3[p->stream] == NULL);
820                 uas->status3[p->stream] = p;
821                 p->status = USB_RET_ASYNC;
822                 break;
823             }
824         } else {
825             st = QTAILQ_FIRST(&uas->results);
826             if (st == NULL) {
827                 assert(uas->status2 == NULL);
828                 uas->status2 = p;
829                 p->status = USB_RET_ASYNC;
830                 break;
831             }
832         }
833         usb_packet_copy(p, &st->status, st->length);
834         QTAILQ_REMOVE(&uas->results, st, next);
835         g_free(st);
836         break;
837     case UAS_PIPE_ID_DATA_IN:
838     case UAS_PIPE_ID_DATA_OUT:
839         if (p->stream) {
840             req = usb_uas_find_request(uas, p->stream);
841         } else {
842             req = (p->ep->nr == UAS_PIPE_ID_DATA_IN)
843                 ? uas->datain2 : uas->dataout2;
844         }
845         if (req == NULL) {
846             if (p->stream) {
847                 assert(uas->data3[p->stream] == NULL);
848                 uas->data3[p->stream] = p;
849                 p->status = USB_RET_ASYNC;
850                 break;
851             } else {
852                 fprintf(stderr, "%s: no inflight request\n", __func__);
853                 p->status = USB_RET_STALL;
854                 break;
855             }
856         }
857         scsi_req_ref(req->req);
858         req->data = p;
859         usb_uas_copy_data(req);
860         if (p->actual_length == p->iov.size || req->complete) {
861             req->data = NULL;
862         } else {
863             req->data_async = true;
864             p->status = USB_RET_ASYNC;
865         }
866         scsi_req_unref(req->req);
867         usb_uas_start_next_transfer(uas);
868         break;
869     default:
870         fprintf(stderr, "%s: invalid endpoint %d\n", __func__, p->ep->nr);
871         p->status = USB_RET_STALL;
872         break;
873     }
874 }
875 
876 static void usb_uas_handle_destroy(USBDevice *dev)
877 {
878     UASDevice *uas = DO_UPCAST(UASDevice, dev, dev);
879 
880     qemu_bh_delete(uas->status_bh);
881 }
882 
883 static int usb_uas_init(USBDevice *dev)
884 {
885     UASDevice *uas = DO_UPCAST(UASDevice, dev, dev);
886 
887     usb_desc_create_serial(dev);
888     usb_desc_init(dev);
889 
890     QTAILQ_INIT(&uas->results);
891     QTAILQ_INIT(&uas->requests);
892     uas->status_bh = qemu_bh_new(usb_uas_send_status_bh, uas);
893 
894     scsi_bus_new(&uas->bus, sizeof(uas->bus), DEVICE(dev),
895                  &usb_uas_scsi_info, NULL);
896 
897     return 0;
898 }
899 
900 static const VMStateDescription vmstate_usb_uas = {
901     .name = "usb-uas",
902     .unmigratable = 1,
903     .fields = (VMStateField[]) {
904         VMSTATE_USB_DEVICE(dev, UASDevice),
905         VMSTATE_END_OF_LIST()
906     }
907 };
908 
909 static Property uas_properties[] = {
910     DEFINE_PROP_UINT32("log-scsi-req", UASDevice, requestlog, 0),
911     DEFINE_PROP_END_OF_LIST(),
912 };
913 
914 static void usb_uas_class_initfn(ObjectClass *klass, void *data)
915 {
916     DeviceClass *dc = DEVICE_CLASS(klass);
917     USBDeviceClass *uc = USB_DEVICE_CLASS(klass);
918 
919     uc->init           = usb_uas_init;
920     uc->product_desc   = desc_strings[STR_PRODUCT];
921     uc->usb_desc       = &desc;
922     uc->cancel_packet  = usb_uas_cancel_io;
923     uc->handle_attach  = usb_desc_attach;
924     uc->handle_reset   = usb_uas_handle_reset;
925     uc->handle_control = usb_uas_handle_control;
926     uc->handle_data    = usb_uas_handle_data;
927     uc->handle_destroy = usb_uas_handle_destroy;
928     set_bit(DEVICE_CATEGORY_STORAGE, dc->categories);
929     dc->fw_name = "storage";
930     dc->vmsd = &vmstate_usb_uas;
931     dc->props = uas_properties;
932 }
933 
934 static const TypeInfo uas_info = {
935     .name          = "usb-uas",
936     .parent        = TYPE_USB_DEVICE,
937     .instance_size = sizeof(UASDevice),
938     .class_init    = usb_uas_class_initfn,
939 };
940 
941 static void usb_uas_register_types(void)
942 {
943     type_register_static(&uas_info);
944 }
945 
946 type_init(usb_uas_register_types)
947