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