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