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