xref: /openbmc/qemu/hw/scsi/vmw_pvscsi.c (revision 500eb6db)
1 /*
2  * QEMU VMWARE PVSCSI paravirtual SCSI bus
3  *
4  * Copyright (c) 2012 Ravello Systems LTD (http://ravellosystems.com)
5  *
6  * Developed by Daynix Computing LTD (http://www.daynix.com)
7  *
8  * Based on implementation by Paolo Bonzini
9  * http://lists.gnu.org/archive/html/qemu-devel/2011-08/msg00729.html
10  *
11  * Authors:
12  * Paolo Bonzini <pbonzini@redhat.com>
13  * Dmitry Fleytman <dmitry@daynix.com>
14  * Yan Vugenfirer <yan@daynix.com>
15  *
16  * This work is licensed under the terms of the GNU GPL, version 2.
17  * See the COPYING file in the top-level directory.
18  *
19  * NOTE about MSI-X:
20  * MSI-X support has been removed for the moment because it leads Windows OS
21  * to crash on startup. The crash happens because Windows driver requires
22  * MSI-X shared memory to be part of the same BAR used for rings state
23  * registers, etc. This is not supported by QEMU infrastructure so separate
24  * BAR created from MSI-X purposes. Windows driver fails to deal with 2 BARs.
25  *
26  */
27 
28 #include "qemu/osdep.h"
29 #include "qapi/error.h"
30 #include "qemu/module.h"
31 #include "hw/scsi/scsi.h"
32 #include "scsi/constants.h"
33 #include "hw/pci/msi.h"
34 #include "vmw_pvscsi.h"
35 #include "trace.h"
36 
37 
38 #define PVSCSI_USE_64BIT         (true)
39 #define PVSCSI_PER_VECTOR_MASK   (false)
40 
41 #define PVSCSI_MAX_DEVS                   (64)
42 #define PVSCSI_MSIX_NUM_VECTORS           (1)
43 
44 #define PVSCSI_MAX_SG_ELEM                2048
45 
46 #define PVSCSI_MAX_CMD_DATA_WORDS \
47     (sizeof(PVSCSICmdDescSetupRings)/sizeof(uint32_t))
48 
49 #define RS_GET_FIELD(m, field) \
50     (ldl_le_pci_dma(&container_of(m, PVSCSIState, rings)->parent_obj, \
51                  (m)->rs_pa + offsetof(struct PVSCSIRingsState, field)))
52 #define RS_SET_FIELD(m, field, val) \
53     (stl_le_pci_dma(&container_of(m, PVSCSIState, rings)->parent_obj, \
54                  (m)->rs_pa + offsetof(struct PVSCSIRingsState, field), val))
55 
56 typedef struct PVSCSIClass {
57     PCIDeviceClass parent_class;
58     DeviceRealize parent_dc_realize;
59 } PVSCSIClass;
60 
61 #define TYPE_PVSCSI "pvscsi"
62 #define PVSCSI(obj) OBJECT_CHECK(PVSCSIState, (obj), TYPE_PVSCSI)
63 
64 #define PVSCSI_DEVICE_CLASS(klass) \
65     OBJECT_CLASS_CHECK(PVSCSIClass, (klass), TYPE_PVSCSI)
66 #define PVSCSI_DEVICE_GET_CLASS(obj) \
67     OBJECT_GET_CLASS(PVSCSIClass, (obj), TYPE_PVSCSI)
68 
69 /* Compatibility flags for migration */
70 #define PVSCSI_COMPAT_OLD_PCI_CONFIGURATION_BIT 0
71 #define PVSCSI_COMPAT_OLD_PCI_CONFIGURATION \
72     (1 << PVSCSI_COMPAT_OLD_PCI_CONFIGURATION_BIT)
73 #define PVSCSI_COMPAT_DISABLE_PCIE_BIT 1
74 #define PVSCSI_COMPAT_DISABLE_PCIE \
75     (1 << PVSCSI_COMPAT_DISABLE_PCIE_BIT)
76 
77 #define PVSCSI_USE_OLD_PCI_CONFIGURATION(s) \
78     ((s)->compat_flags & PVSCSI_COMPAT_OLD_PCI_CONFIGURATION)
79 #define PVSCSI_MSI_OFFSET(s) \
80     (PVSCSI_USE_OLD_PCI_CONFIGURATION(s) ? 0x50 : 0x7c)
81 #define PVSCSI_EXP_EP_OFFSET (0x40)
82 
83 typedef struct PVSCSIRingInfo {
84     uint64_t            rs_pa;
85     uint32_t            txr_len_mask;
86     uint32_t            rxr_len_mask;
87     uint32_t            msg_len_mask;
88     uint64_t            req_ring_pages_pa[PVSCSI_SETUP_RINGS_MAX_NUM_PAGES];
89     uint64_t            cmp_ring_pages_pa[PVSCSI_SETUP_RINGS_MAX_NUM_PAGES];
90     uint64_t            msg_ring_pages_pa[PVSCSI_SETUP_MSG_RING_MAX_NUM_PAGES];
91     uint64_t            consumed_ptr;
92     uint64_t            filled_cmp_ptr;
93     uint64_t            filled_msg_ptr;
94 } PVSCSIRingInfo;
95 
96 typedef struct PVSCSISGState {
97     hwaddr elemAddr;
98     hwaddr dataAddr;
99     uint32_t resid;
100 } PVSCSISGState;
101 
102 typedef QTAILQ_HEAD(, PVSCSIRequest) PVSCSIRequestList;
103 
104 typedef struct {
105     PCIDevice parent_obj;
106     MemoryRegion io_space;
107     SCSIBus bus;
108     QEMUBH *completion_worker;
109     PVSCSIRequestList pending_queue;
110     PVSCSIRequestList completion_queue;
111 
112     uint64_t reg_interrupt_status;        /* Interrupt status register value */
113     uint64_t reg_interrupt_enabled;       /* Interrupt mask register value   */
114     uint64_t reg_command_status;          /* Command status register value   */
115 
116     /* Command data adoption mechanism */
117     uint64_t curr_cmd;                   /* Last command arrived             */
118     uint32_t curr_cmd_data_cntr;         /* Amount of data for last command  */
119 
120     /* Collector for current command data */
121     uint32_t curr_cmd_data[PVSCSI_MAX_CMD_DATA_WORDS];
122 
123     uint8_t rings_info_valid;            /* Whether data rings initialized   */
124     uint8_t msg_ring_info_valid;         /* Whether message ring initialized */
125     uint8_t use_msg;                     /* Whether to use message ring      */
126 
127     uint8_t msi_used;                    /* For migration compatibility      */
128     PVSCSIRingInfo rings;                /* Data transfer rings manager      */
129     uint32_t resetting;                  /* Reset in progress                */
130 
131     uint32_t compat_flags;
132 } PVSCSIState;
133 
134 typedef struct PVSCSIRequest {
135     SCSIRequest *sreq;
136     PVSCSIState *dev;
137     uint8_t sense_key;
138     uint8_t completed;
139     int lun;
140     QEMUSGList sgl;
141     PVSCSISGState sg;
142     struct PVSCSIRingReqDesc req;
143     struct PVSCSIRingCmpDesc cmp;
144     QTAILQ_ENTRY(PVSCSIRequest) next;
145 } PVSCSIRequest;
146 
147 /* Integer binary logarithm */
148 static int
149 pvscsi_log2(uint32_t input)
150 {
151     int log = 0;
152     assert(input > 0);
153     while (input >> ++log) {
154     }
155     return log;
156 }
157 
158 static void
159 pvscsi_ring_init_data(PVSCSIRingInfo *m, PVSCSICmdDescSetupRings *ri)
160 {
161     int i;
162     uint32_t txr_len_log2, rxr_len_log2;
163     uint32_t req_ring_size, cmp_ring_size;
164     m->rs_pa = ri->ringsStatePPN << VMW_PAGE_SHIFT;
165 
166     req_ring_size = ri->reqRingNumPages * PVSCSI_MAX_NUM_REQ_ENTRIES_PER_PAGE;
167     cmp_ring_size = ri->cmpRingNumPages * PVSCSI_MAX_NUM_CMP_ENTRIES_PER_PAGE;
168     txr_len_log2 = pvscsi_log2(req_ring_size - 1);
169     rxr_len_log2 = pvscsi_log2(cmp_ring_size - 1);
170 
171     m->txr_len_mask = MASK(txr_len_log2);
172     m->rxr_len_mask = MASK(rxr_len_log2);
173 
174     m->consumed_ptr = 0;
175     m->filled_cmp_ptr = 0;
176 
177     for (i = 0; i < ri->reqRingNumPages; i++) {
178         m->req_ring_pages_pa[i] = ri->reqRingPPNs[i] << VMW_PAGE_SHIFT;
179     }
180 
181     for (i = 0; i < ri->cmpRingNumPages; i++) {
182         m->cmp_ring_pages_pa[i] = ri->cmpRingPPNs[i] << VMW_PAGE_SHIFT;
183     }
184 
185     RS_SET_FIELD(m, reqProdIdx, 0);
186     RS_SET_FIELD(m, reqConsIdx, 0);
187     RS_SET_FIELD(m, reqNumEntriesLog2, txr_len_log2);
188 
189     RS_SET_FIELD(m, cmpProdIdx, 0);
190     RS_SET_FIELD(m, cmpConsIdx, 0);
191     RS_SET_FIELD(m, cmpNumEntriesLog2, rxr_len_log2);
192 
193     trace_pvscsi_ring_init_data(txr_len_log2, rxr_len_log2);
194 
195     /* Flush ring state page changes */
196     smp_wmb();
197 }
198 
199 static int
200 pvscsi_ring_init_msg(PVSCSIRingInfo *m, PVSCSICmdDescSetupMsgRing *ri)
201 {
202     int i;
203     uint32_t len_log2;
204     uint32_t ring_size;
205 
206     if (!ri->numPages || ri->numPages > PVSCSI_SETUP_MSG_RING_MAX_NUM_PAGES) {
207         return -1;
208     }
209     ring_size = ri->numPages * PVSCSI_MAX_NUM_MSG_ENTRIES_PER_PAGE;
210     len_log2 = pvscsi_log2(ring_size - 1);
211 
212     m->msg_len_mask = MASK(len_log2);
213 
214     m->filled_msg_ptr = 0;
215 
216     for (i = 0; i < ri->numPages; i++) {
217         m->msg_ring_pages_pa[i] = ri->ringPPNs[i] << VMW_PAGE_SHIFT;
218     }
219 
220     RS_SET_FIELD(m, msgProdIdx, 0);
221     RS_SET_FIELD(m, msgConsIdx, 0);
222     RS_SET_FIELD(m, msgNumEntriesLog2, len_log2);
223 
224     trace_pvscsi_ring_init_msg(len_log2);
225 
226     /* Flush ring state page changes */
227     smp_wmb();
228 
229     return 0;
230 }
231 
232 static void
233 pvscsi_ring_cleanup(PVSCSIRingInfo *mgr)
234 {
235     mgr->rs_pa = 0;
236     mgr->txr_len_mask = 0;
237     mgr->rxr_len_mask = 0;
238     mgr->msg_len_mask = 0;
239     mgr->consumed_ptr = 0;
240     mgr->filled_cmp_ptr = 0;
241     mgr->filled_msg_ptr = 0;
242     memset(mgr->req_ring_pages_pa, 0, sizeof(mgr->req_ring_pages_pa));
243     memset(mgr->cmp_ring_pages_pa, 0, sizeof(mgr->cmp_ring_pages_pa));
244     memset(mgr->msg_ring_pages_pa, 0, sizeof(mgr->msg_ring_pages_pa));
245 }
246 
247 static hwaddr
248 pvscsi_ring_pop_req_descr(PVSCSIRingInfo *mgr)
249 {
250     uint32_t ready_ptr = RS_GET_FIELD(mgr, reqProdIdx);
251     uint32_t ring_size = PVSCSI_MAX_NUM_PAGES_REQ_RING
252                             * PVSCSI_MAX_NUM_REQ_ENTRIES_PER_PAGE;
253 
254     if (ready_ptr != mgr->consumed_ptr
255         && ready_ptr - mgr->consumed_ptr < ring_size) {
256         uint32_t next_ready_ptr =
257             mgr->consumed_ptr++ & mgr->txr_len_mask;
258         uint32_t next_ready_page =
259             next_ready_ptr / PVSCSI_MAX_NUM_REQ_ENTRIES_PER_PAGE;
260         uint32_t inpage_idx =
261             next_ready_ptr % PVSCSI_MAX_NUM_REQ_ENTRIES_PER_PAGE;
262 
263         return mgr->req_ring_pages_pa[next_ready_page] +
264                inpage_idx * sizeof(PVSCSIRingReqDesc);
265     } else {
266         return 0;
267     }
268 }
269 
270 static void
271 pvscsi_ring_flush_req(PVSCSIRingInfo *mgr)
272 {
273     RS_SET_FIELD(mgr, reqConsIdx, mgr->consumed_ptr);
274 }
275 
276 static hwaddr
277 pvscsi_ring_pop_cmp_descr(PVSCSIRingInfo *mgr)
278 {
279     /*
280      * According to Linux driver code it explicitly verifies that number
281      * of requests being processed by device is less then the size of
282      * completion queue, so device may omit completion queue overflow
283      * conditions check. We assume that this is true for other (Windows)
284      * drivers as well.
285      */
286 
287     uint32_t free_cmp_ptr =
288         mgr->filled_cmp_ptr++ & mgr->rxr_len_mask;
289     uint32_t free_cmp_page =
290         free_cmp_ptr / PVSCSI_MAX_NUM_CMP_ENTRIES_PER_PAGE;
291     uint32_t inpage_idx =
292         free_cmp_ptr % PVSCSI_MAX_NUM_CMP_ENTRIES_PER_PAGE;
293     return mgr->cmp_ring_pages_pa[free_cmp_page] +
294            inpage_idx * sizeof(PVSCSIRingCmpDesc);
295 }
296 
297 static hwaddr
298 pvscsi_ring_pop_msg_descr(PVSCSIRingInfo *mgr)
299 {
300     uint32_t free_msg_ptr =
301         mgr->filled_msg_ptr++ & mgr->msg_len_mask;
302     uint32_t free_msg_page =
303         free_msg_ptr / PVSCSI_MAX_NUM_MSG_ENTRIES_PER_PAGE;
304     uint32_t inpage_idx =
305         free_msg_ptr % PVSCSI_MAX_NUM_MSG_ENTRIES_PER_PAGE;
306     return mgr->msg_ring_pages_pa[free_msg_page] +
307            inpage_idx * sizeof(PVSCSIRingMsgDesc);
308 }
309 
310 static void
311 pvscsi_ring_flush_cmp(PVSCSIRingInfo *mgr)
312 {
313     /* Flush descriptor changes */
314     smp_wmb();
315 
316     trace_pvscsi_ring_flush_cmp(mgr->filled_cmp_ptr);
317 
318     RS_SET_FIELD(mgr, cmpProdIdx, mgr->filled_cmp_ptr);
319 }
320 
321 static bool
322 pvscsi_ring_msg_has_room(PVSCSIRingInfo *mgr)
323 {
324     uint32_t prodIdx = RS_GET_FIELD(mgr, msgProdIdx);
325     uint32_t consIdx = RS_GET_FIELD(mgr, msgConsIdx);
326 
327     return (prodIdx - consIdx) < (mgr->msg_len_mask + 1);
328 }
329 
330 static void
331 pvscsi_ring_flush_msg(PVSCSIRingInfo *mgr)
332 {
333     /* Flush descriptor changes */
334     smp_wmb();
335 
336     trace_pvscsi_ring_flush_msg(mgr->filled_msg_ptr);
337 
338     RS_SET_FIELD(mgr, msgProdIdx, mgr->filled_msg_ptr);
339 }
340 
341 static void
342 pvscsi_reset_state(PVSCSIState *s)
343 {
344     s->curr_cmd = PVSCSI_CMD_FIRST;
345     s->curr_cmd_data_cntr = 0;
346     s->reg_command_status = PVSCSI_COMMAND_PROCESSING_SUCCEEDED;
347     s->reg_interrupt_status = 0;
348     pvscsi_ring_cleanup(&s->rings);
349     s->rings_info_valid = FALSE;
350     s->msg_ring_info_valid = FALSE;
351     QTAILQ_INIT(&s->pending_queue);
352     QTAILQ_INIT(&s->completion_queue);
353 }
354 
355 static void
356 pvscsi_update_irq_status(PVSCSIState *s)
357 {
358     PCIDevice *d = PCI_DEVICE(s);
359     bool should_raise = s->reg_interrupt_enabled & s->reg_interrupt_status;
360 
361     trace_pvscsi_update_irq_level(should_raise, s->reg_interrupt_enabled,
362                                   s->reg_interrupt_status);
363 
364     if (msi_enabled(d)) {
365         if (should_raise) {
366             trace_pvscsi_update_irq_msi();
367             msi_notify(d, PVSCSI_VECTOR_COMPLETION);
368         }
369         return;
370     }
371 
372     pci_set_irq(d, !!should_raise);
373 }
374 
375 static void
376 pvscsi_raise_completion_interrupt(PVSCSIState *s)
377 {
378     s->reg_interrupt_status |= PVSCSI_INTR_CMPL_0;
379 
380     /* Memory barrier to flush interrupt status register changes*/
381     smp_wmb();
382 
383     pvscsi_update_irq_status(s);
384 }
385 
386 static void
387 pvscsi_raise_message_interrupt(PVSCSIState *s)
388 {
389     s->reg_interrupt_status |= PVSCSI_INTR_MSG_0;
390 
391     /* Memory barrier to flush interrupt status register changes*/
392     smp_wmb();
393 
394     pvscsi_update_irq_status(s);
395 }
396 
397 static void
398 pvscsi_cmp_ring_put(PVSCSIState *s, struct PVSCSIRingCmpDesc *cmp_desc)
399 {
400     hwaddr cmp_descr_pa;
401 
402     cmp_descr_pa = pvscsi_ring_pop_cmp_descr(&s->rings);
403     trace_pvscsi_cmp_ring_put(cmp_descr_pa);
404     cpu_physical_memory_write(cmp_descr_pa, (void *)cmp_desc,
405                               sizeof(*cmp_desc));
406 }
407 
408 static void
409 pvscsi_msg_ring_put(PVSCSIState *s, struct PVSCSIRingMsgDesc *msg_desc)
410 {
411     hwaddr msg_descr_pa;
412 
413     msg_descr_pa = pvscsi_ring_pop_msg_descr(&s->rings);
414     trace_pvscsi_msg_ring_put(msg_descr_pa);
415     cpu_physical_memory_write(msg_descr_pa, (void *)msg_desc,
416                               sizeof(*msg_desc));
417 }
418 
419 static void
420 pvscsi_process_completion_queue(void *opaque)
421 {
422     PVSCSIState *s = opaque;
423     PVSCSIRequest *pvscsi_req;
424     bool has_completed = false;
425 
426     while (!QTAILQ_EMPTY(&s->completion_queue)) {
427         pvscsi_req = QTAILQ_FIRST(&s->completion_queue);
428         QTAILQ_REMOVE(&s->completion_queue, pvscsi_req, next);
429         pvscsi_cmp_ring_put(s, &pvscsi_req->cmp);
430         g_free(pvscsi_req);
431         has_completed = true;
432     }
433 
434     if (has_completed) {
435         pvscsi_ring_flush_cmp(&s->rings);
436         pvscsi_raise_completion_interrupt(s);
437     }
438 }
439 
440 static void
441 pvscsi_reset_adapter(PVSCSIState *s)
442 {
443     s->resetting++;
444     qbus_reset_all(BUS(&s->bus));
445     s->resetting--;
446     pvscsi_process_completion_queue(s);
447     assert(QTAILQ_EMPTY(&s->pending_queue));
448     pvscsi_reset_state(s);
449 }
450 
451 static void
452 pvscsi_schedule_completion_processing(PVSCSIState *s)
453 {
454     /* Try putting more complete requests on the ring. */
455     if (!QTAILQ_EMPTY(&s->completion_queue)) {
456         qemu_bh_schedule(s->completion_worker);
457     }
458 }
459 
460 static void
461 pvscsi_complete_request(PVSCSIState *s, PVSCSIRequest *r)
462 {
463     assert(!r->completed);
464 
465     trace_pvscsi_complete_request(r->cmp.context, r->cmp.dataLen,
466                                   r->sense_key);
467     if (r->sreq != NULL) {
468         scsi_req_unref(r->sreq);
469         r->sreq = NULL;
470     }
471     r->completed = 1;
472     QTAILQ_REMOVE(&s->pending_queue, r, next);
473     QTAILQ_INSERT_TAIL(&s->completion_queue, r, next);
474     pvscsi_schedule_completion_processing(s);
475 }
476 
477 static QEMUSGList *pvscsi_get_sg_list(SCSIRequest *r)
478 {
479     PVSCSIRequest *req = r->hba_private;
480 
481     trace_pvscsi_get_sg_list(req->sgl.nsg, req->sgl.size);
482 
483     return &req->sgl;
484 }
485 
486 static void
487 pvscsi_get_next_sg_elem(PVSCSISGState *sg)
488 {
489     struct PVSCSISGElement elem;
490 
491     cpu_physical_memory_read(sg->elemAddr, (void *)&elem, sizeof(elem));
492     if ((elem.flags & ~PVSCSI_KNOWN_FLAGS) != 0) {
493         /*
494             * There is PVSCSI_SGE_FLAG_CHAIN_ELEMENT flag described in
495             * header file but its value is unknown. This flag requires
496             * additional processing, so we put warning here to catch it
497             * some day and make proper implementation
498             */
499         trace_pvscsi_get_next_sg_elem(elem.flags);
500     }
501 
502     sg->elemAddr += sizeof(elem);
503     sg->dataAddr = elem.addr;
504     sg->resid = elem.length;
505 }
506 
507 static void
508 pvscsi_write_sense(PVSCSIRequest *r, uint8_t *sense, int len)
509 {
510     r->cmp.senseLen = MIN(r->req.senseLen, len);
511     r->sense_key = sense[(sense[0] & 2) ? 1 : 2];
512     cpu_physical_memory_write(r->req.senseAddr, sense, r->cmp.senseLen);
513 }
514 
515 static void
516 pvscsi_command_complete(SCSIRequest *req, uint32_t status, size_t resid)
517 {
518     PVSCSIRequest *pvscsi_req = req->hba_private;
519     PVSCSIState *s;
520 
521     if (!pvscsi_req) {
522         trace_pvscsi_command_complete_not_found(req->tag);
523         return;
524     }
525     s = pvscsi_req->dev;
526 
527     if (resid) {
528         /* Short transfer.  */
529         trace_pvscsi_command_complete_data_run();
530         pvscsi_req->cmp.hostStatus = BTSTAT_DATARUN;
531     }
532 
533     pvscsi_req->cmp.scsiStatus = status;
534     if (pvscsi_req->cmp.scsiStatus == CHECK_CONDITION) {
535         uint8_t sense[SCSI_SENSE_BUF_SIZE];
536         int sense_len =
537             scsi_req_get_sense(pvscsi_req->sreq, sense, sizeof(sense));
538 
539         trace_pvscsi_command_complete_sense_len(sense_len);
540         pvscsi_write_sense(pvscsi_req, sense, sense_len);
541     }
542     qemu_sglist_destroy(&pvscsi_req->sgl);
543     pvscsi_complete_request(s, pvscsi_req);
544 }
545 
546 static void
547 pvscsi_send_msg(PVSCSIState *s, SCSIDevice *dev, uint32_t msg_type)
548 {
549     if (s->msg_ring_info_valid && pvscsi_ring_msg_has_room(&s->rings)) {
550         PVSCSIMsgDescDevStatusChanged msg = {0};
551 
552         msg.type = msg_type;
553         msg.bus = dev->channel;
554         msg.target = dev->id;
555         msg.lun[1] = dev->lun;
556 
557         pvscsi_msg_ring_put(s, (PVSCSIRingMsgDesc *)&msg);
558         pvscsi_ring_flush_msg(&s->rings);
559         pvscsi_raise_message_interrupt(s);
560     }
561 }
562 
563 static void
564 pvscsi_hotplug(HotplugHandler *hotplug_dev, DeviceState *dev, Error **errp)
565 {
566     PVSCSIState *s = PVSCSI(hotplug_dev);
567 
568     pvscsi_send_msg(s, SCSI_DEVICE(dev), PVSCSI_MSG_DEV_ADDED);
569 }
570 
571 static void
572 pvscsi_hot_unplug(HotplugHandler *hotplug_dev, DeviceState *dev, Error **errp)
573 {
574     PVSCSIState *s = PVSCSI(hotplug_dev);
575 
576     pvscsi_send_msg(s, SCSI_DEVICE(dev), PVSCSI_MSG_DEV_REMOVED);
577     qdev_simple_device_unplug_cb(hotplug_dev, dev, errp);
578 }
579 
580 static void
581 pvscsi_request_cancelled(SCSIRequest *req)
582 {
583     PVSCSIRequest *pvscsi_req = req->hba_private;
584     PVSCSIState *s = pvscsi_req->dev;
585 
586     if (pvscsi_req->completed) {
587         return;
588     }
589 
590    if (pvscsi_req->dev->resetting) {
591        pvscsi_req->cmp.hostStatus = BTSTAT_BUSRESET;
592     } else {
593        pvscsi_req->cmp.hostStatus = BTSTAT_ABORTQUEUE;
594     }
595 
596     pvscsi_complete_request(s, pvscsi_req);
597 }
598 
599 static SCSIDevice*
600 pvscsi_device_find(PVSCSIState *s, int channel, int target,
601                    uint8_t *requested_lun, uint8_t *target_lun)
602 {
603     if (requested_lun[0] || requested_lun[2] || requested_lun[3] ||
604         requested_lun[4] || requested_lun[5] || requested_lun[6] ||
605         requested_lun[7] || (target > PVSCSI_MAX_DEVS)) {
606         return NULL;
607     } else {
608         *target_lun = requested_lun[1];
609         return scsi_device_find(&s->bus, channel, target, *target_lun);
610     }
611 }
612 
613 static PVSCSIRequest *
614 pvscsi_queue_pending_descriptor(PVSCSIState *s, SCSIDevice **d,
615                                 struct PVSCSIRingReqDesc *descr)
616 {
617     PVSCSIRequest *pvscsi_req;
618     uint8_t lun;
619 
620     pvscsi_req = g_malloc0(sizeof(*pvscsi_req));
621     pvscsi_req->dev = s;
622     pvscsi_req->req = *descr;
623     pvscsi_req->cmp.context = pvscsi_req->req.context;
624     QTAILQ_INSERT_TAIL(&s->pending_queue, pvscsi_req, next);
625 
626     *d = pvscsi_device_find(s, descr->bus, descr->target, descr->lun, &lun);
627     if (*d) {
628         pvscsi_req->lun = lun;
629     }
630 
631     return pvscsi_req;
632 }
633 
634 static void
635 pvscsi_convert_sglist(PVSCSIRequest *r)
636 {
637     uint32_t chunk_size, elmcnt = 0;
638     uint64_t data_length = r->req.dataLen;
639     PVSCSISGState sg = r->sg;
640     while (data_length && elmcnt < PVSCSI_MAX_SG_ELEM) {
641         while (!sg.resid && elmcnt++ < PVSCSI_MAX_SG_ELEM) {
642             pvscsi_get_next_sg_elem(&sg);
643             trace_pvscsi_convert_sglist(r->req.context, r->sg.dataAddr,
644                                         r->sg.resid);
645         }
646         chunk_size = MIN(data_length, sg.resid);
647         if (chunk_size) {
648             qemu_sglist_add(&r->sgl, sg.dataAddr, chunk_size);
649         }
650 
651         sg.dataAddr += chunk_size;
652         data_length -= chunk_size;
653         sg.resid -= chunk_size;
654     }
655 }
656 
657 static void
658 pvscsi_build_sglist(PVSCSIState *s, PVSCSIRequest *r)
659 {
660     PCIDevice *d = PCI_DEVICE(s);
661 
662     pci_dma_sglist_init(&r->sgl, d, 1);
663     if (r->req.flags & PVSCSI_FLAG_CMD_WITH_SG_LIST) {
664         pvscsi_convert_sglist(r);
665     } else {
666         qemu_sglist_add(&r->sgl, r->req.dataAddr, r->req.dataLen);
667     }
668 }
669 
670 static void
671 pvscsi_process_request_descriptor(PVSCSIState *s,
672                                   struct PVSCSIRingReqDesc *descr)
673 {
674     SCSIDevice *d;
675     PVSCSIRequest *r = pvscsi_queue_pending_descriptor(s, &d, descr);
676     int64_t n;
677 
678     trace_pvscsi_process_req_descr(descr->cdb[0], descr->context);
679 
680     if (!d) {
681         r->cmp.hostStatus = BTSTAT_SELTIMEO;
682         trace_pvscsi_process_req_descr_unknown_device();
683         pvscsi_complete_request(s, r);
684         return;
685     }
686 
687     if (descr->flags & PVSCSI_FLAG_CMD_WITH_SG_LIST) {
688         r->sg.elemAddr = descr->dataAddr;
689     }
690 
691     r->sreq = scsi_req_new(d, descr->context, r->lun, descr->cdb, r);
692     if (r->sreq->cmd.mode == SCSI_XFER_FROM_DEV &&
693         (descr->flags & PVSCSI_FLAG_CMD_DIR_TODEVICE)) {
694         r->cmp.hostStatus = BTSTAT_BADMSG;
695         trace_pvscsi_process_req_descr_invalid_dir();
696         scsi_req_cancel(r->sreq);
697         return;
698     }
699     if (r->sreq->cmd.mode == SCSI_XFER_TO_DEV &&
700         (descr->flags & PVSCSI_FLAG_CMD_DIR_TOHOST)) {
701         r->cmp.hostStatus = BTSTAT_BADMSG;
702         trace_pvscsi_process_req_descr_invalid_dir();
703         scsi_req_cancel(r->sreq);
704         return;
705     }
706 
707     pvscsi_build_sglist(s, r);
708     n = scsi_req_enqueue(r->sreq);
709 
710     if (n) {
711         scsi_req_continue(r->sreq);
712     }
713 }
714 
715 static void
716 pvscsi_process_io(PVSCSIState *s)
717 {
718     PVSCSIRingReqDesc descr;
719     hwaddr next_descr_pa;
720 
721     assert(s->rings_info_valid);
722     while ((next_descr_pa = pvscsi_ring_pop_req_descr(&s->rings)) != 0) {
723 
724         /* Only read after production index verification */
725         smp_rmb();
726 
727         trace_pvscsi_process_io(next_descr_pa);
728         cpu_physical_memory_read(next_descr_pa, &descr, sizeof(descr));
729         pvscsi_process_request_descriptor(s, &descr);
730     }
731 
732     pvscsi_ring_flush_req(&s->rings);
733 }
734 
735 static void
736 pvscsi_dbg_dump_tx_rings_config(PVSCSICmdDescSetupRings *rc)
737 {
738     int i;
739     trace_pvscsi_tx_rings_ppn("Rings State", rc->ringsStatePPN);
740 
741     trace_pvscsi_tx_rings_num_pages("Request Ring", rc->reqRingNumPages);
742     for (i = 0; i < rc->reqRingNumPages; i++) {
743         trace_pvscsi_tx_rings_ppn("Request Ring", rc->reqRingPPNs[i]);
744     }
745 
746     trace_pvscsi_tx_rings_num_pages("Confirm Ring", rc->cmpRingNumPages);
747     for (i = 0; i < rc->cmpRingNumPages; i++) {
748         trace_pvscsi_tx_rings_ppn("Confirm Ring", rc->cmpRingPPNs[i]);
749     }
750 }
751 
752 static uint64_t
753 pvscsi_on_cmd_config(PVSCSIState *s)
754 {
755     trace_pvscsi_on_cmd_noimpl("PVSCSI_CMD_CONFIG");
756     return PVSCSI_COMMAND_PROCESSING_FAILED;
757 }
758 
759 static uint64_t
760 pvscsi_on_cmd_unplug(PVSCSIState *s)
761 {
762     trace_pvscsi_on_cmd_noimpl("PVSCSI_CMD_DEVICE_UNPLUG");
763     return PVSCSI_COMMAND_PROCESSING_FAILED;
764 }
765 
766 static uint64_t
767 pvscsi_on_issue_scsi(PVSCSIState *s)
768 {
769     trace_pvscsi_on_cmd_noimpl("PVSCSI_CMD_ISSUE_SCSI");
770     return PVSCSI_COMMAND_PROCESSING_FAILED;
771 }
772 
773 static uint64_t
774 pvscsi_on_cmd_setup_rings(PVSCSIState *s)
775 {
776     PVSCSICmdDescSetupRings *rc =
777         (PVSCSICmdDescSetupRings *) s->curr_cmd_data;
778 
779     trace_pvscsi_on_cmd_arrived("PVSCSI_CMD_SETUP_RINGS");
780 
781     if (!rc->reqRingNumPages
782         || rc->reqRingNumPages > PVSCSI_SETUP_RINGS_MAX_NUM_PAGES
783         || !rc->cmpRingNumPages
784         || rc->cmpRingNumPages > PVSCSI_SETUP_RINGS_MAX_NUM_PAGES) {
785         return PVSCSI_COMMAND_PROCESSING_FAILED;
786     }
787 
788     pvscsi_dbg_dump_tx_rings_config(rc);
789     pvscsi_ring_init_data(&s->rings, rc);
790 
791     s->rings_info_valid = TRUE;
792     return PVSCSI_COMMAND_PROCESSING_SUCCEEDED;
793 }
794 
795 static uint64_t
796 pvscsi_on_cmd_abort(PVSCSIState *s)
797 {
798     PVSCSICmdDescAbortCmd *cmd = (PVSCSICmdDescAbortCmd *) s->curr_cmd_data;
799     PVSCSIRequest *r, *next;
800 
801     trace_pvscsi_on_cmd_abort(cmd->context, cmd->target);
802 
803     QTAILQ_FOREACH_SAFE(r, &s->pending_queue, next, next) {
804         if (r->req.context == cmd->context) {
805             break;
806         }
807     }
808     if (r) {
809         assert(!r->completed);
810         r->cmp.hostStatus = BTSTAT_ABORTQUEUE;
811         scsi_req_cancel(r->sreq);
812     }
813 
814     return PVSCSI_COMMAND_PROCESSING_SUCCEEDED;
815 }
816 
817 static uint64_t
818 pvscsi_on_cmd_unknown(PVSCSIState *s)
819 {
820     trace_pvscsi_on_cmd_unknown_data(s->curr_cmd_data[0]);
821     return PVSCSI_COMMAND_PROCESSING_FAILED;
822 }
823 
824 static uint64_t
825 pvscsi_on_cmd_reset_device(PVSCSIState *s)
826 {
827     uint8_t target_lun = 0;
828     struct PVSCSICmdDescResetDevice *cmd =
829         (struct PVSCSICmdDescResetDevice *) s->curr_cmd_data;
830     SCSIDevice *sdev;
831 
832     sdev = pvscsi_device_find(s, 0, cmd->target, cmd->lun, &target_lun);
833 
834     trace_pvscsi_on_cmd_reset_dev(cmd->target, (int) target_lun, sdev);
835 
836     if (sdev != NULL) {
837         s->resetting++;
838         device_reset(&sdev->qdev);
839         s->resetting--;
840         return PVSCSI_COMMAND_PROCESSING_SUCCEEDED;
841     }
842 
843     return PVSCSI_COMMAND_PROCESSING_FAILED;
844 }
845 
846 static uint64_t
847 pvscsi_on_cmd_reset_bus(PVSCSIState *s)
848 {
849     trace_pvscsi_on_cmd_arrived("PVSCSI_CMD_RESET_BUS");
850 
851     s->resetting++;
852     qbus_reset_all(BUS(&s->bus));
853     s->resetting--;
854     return PVSCSI_COMMAND_PROCESSING_SUCCEEDED;
855 }
856 
857 static uint64_t
858 pvscsi_on_cmd_setup_msg_ring(PVSCSIState *s)
859 {
860     PVSCSICmdDescSetupMsgRing *rc =
861         (PVSCSICmdDescSetupMsgRing *) s->curr_cmd_data;
862 
863     trace_pvscsi_on_cmd_arrived("PVSCSI_CMD_SETUP_MSG_RING");
864 
865     if (!s->use_msg) {
866         return PVSCSI_COMMAND_PROCESSING_FAILED;
867     }
868 
869     if (s->rings_info_valid) {
870         if (pvscsi_ring_init_msg(&s->rings, rc) < 0) {
871             return PVSCSI_COMMAND_PROCESSING_FAILED;
872         }
873         s->msg_ring_info_valid = TRUE;
874     }
875     return sizeof(PVSCSICmdDescSetupMsgRing) / sizeof(uint32_t);
876 }
877 
878 static uint64_t
879 pvscsi_on_cmd_adapter_reset(PVSCSIState *s)
880 {
881     trace_pvscsi_on_cmd_arrived("PVSCSI_CMD_ADAPTER_RESET");
882 
883     pvscsi_reset_adapter(s);
884     return PVSCSI_COMMAND_PROCESSING_SUCCEEDED;
885 }
886 
887 static const struct {
888     int       data_size;
889     uint64_t  (*handler_fn)(PVSCSIState *s);
890 } pvscsi_commands[] = {
891     [PVSCSI_CMD_FIRST] = {
892         .data_size = 0,
893         .handler_fn = pvscsi_on_cmd_unknown,
894     },
895 
896     /* Not implemented, data size defined based on what arrives on windows */
897     [PVSCSI_CMD_CONFIG] = {
898         .data_size = 6 * sizeof(uint32_t),
899         .handler_fn = pvscsi_on_cmd_config,
900     },
901 
902     /* Command not implemented, data size is unknown */
903     [PVSCSI_CMD_ISSUE_SCSI] = {
904         .data_size = 0,
905         .handler_fn = pvscsi_on_issue_scsi,
906     },
907 
908     /* Command not implemented, data size is unknown */
909     [PVSCSI_CMD_DEVICE_UNPLUG] = {
910         .data_size = 0,
911         .handler_fn = pvscsi_on_cmd_unplug,
912     },
913 
914     [PVSCSI_CMD_SETUP_RINGS] = {
915         .data_size = sizeof(PVSCSICmdDescSetupRings),
916         .handler_fn = pvscsi_on_cmd_setup_rings,
917     },
918 
919     [PVSCSI_CMD_RESET_DEVICE] = {
920         .data_size = sizeof(struct PVSCSICmdDescResetDevice),
921         .handler_fn = pvscsi_on_cmd_reset_device,
922     },
923 
924     [PVSCSI_CMD_RESET_BUS] = {
925         .data_size = 0,
926         .handler_fn = pvscsi_on_cmd_reset_bus,
927     },
928 
929     [PVSCSI_CMD_SETUP_MSG_RING] = {
930         .data_size = sizeof(PVSCSICmdDescSetupMsgRing),
931         .handler_fn = pvscsi_on_cmd_setup_msg_ring,
932     },
933 
934     [PVSCSI_CMD_ADAPTER_RESET] = {
935         .data_size = 0,
936         .handler_fn = pvscsi_on_cmd_adapter_reset,
937     },
938 
939     [PVSCSI_CMD_ABORT_CMD] = {
940         .data_size = sizeof(struct PVSCSICmdDescAbortCmd),
941         .handler_fn = pvscsi_on_cmd_abort,
942     },
943 };
944 
945 static void
946 pvscsi_do_command_processing(PVSCSIState *s)
947 {
948     size_t bytes_arrived = s->curr_cmd_data_cntr * sizeof(uint32_t);
949 
950     assert(s->curr_cmd < PVSCSI_CMD_LAST);
951     if (bytes_arrived >= pvscsi_commands[s->curr_cmd].data_size) {
952         s->reg_command_status = pvscsi_commands[s->curr_cmd].handler_fn(s);
953         s->curr_cmd = PVSCSI_CMD_FIRST;
954         s->curr_cmd_data_cntr   = 0;
955     }
956 }
957 
958 static void
959 pvscsi_on_command_data(PVSCSIState *s, uint32_t value)
960 {
961     size_t bytes_arrived = s->curr_cmd_data_cntr * sizeof(uint32_t);
962 
963     assert(bytes_arrived < sizeof(s->curr_cmd_data));
964     s->curr_cmd_data[s->curr_cmd_data_cntr++] = value;
965 
966     pvscsi_do_command_processing(s);
967 }
968 
969 static void
970 pvscsi_on_command(PVSCSIState *s, uint64_t cmd_id)
971 {
972     if ((cmd_id > PVSCSI_CMD_FIRST) && (cmd_id < PVSCSI_CMD_LAST)) {
973         s->curr_cmd = cmd_id;
974     } else {
975         s->curr_cmd = PVSCSI_CMD_FIRST;
976         trace_pvscsi_on_cmd_unknown(cmd_id);
977     }
978 
979     s->curr_cmd_data_cntr = 0;
980     s->reg_command_status = PVSCSI_COMMAND_NOT_ENOUGH_DATA;
981 
982     pvscsi_do_command_processing(s);
983 }
984 
985 static void
986 pvscsi_io_write(void *opaque, hwaddr addr,
987                 uint64_t val, unsigned size)
988 {
989     PVSCSIState *s = opaque;
990 
991     switch (addr) {
992     case PVSCSI_REG_OFFSET_COMMAND:
993         pvscsi_on_command(s, val);
994         break;
995 
996     case PVSCSI_REG_OFFSET_COMMAND_DATA:
997         pvscsi_on_command_data(s, (uint32_t) val);
998         break;
999 
1000     case PVSCSI_REG_OFFSET_INTR_STATUS:
1001         trace_pvscsi_io_write("PVSCSI_REG_OFFSET_INTR_STATUS", val);
1002         s->reg_interrupt_status &= ~val;
1003         pvscsi_update_irq_status(s);
1004         pvscsi_schedule_completion_processing(s);
1005         break;
1006 
1007     case PVSCSI_REG_OFFSET_INTR_MASK:
1008         trace_pvscsi_io_write("PVSCSI_REG_OFFSET_INTR_MASK", val);
1009         s->reg_interrupt_enabled = val;
1010         pvscsi_update_irq_status(s);
1011         break;
1012 
1013     case PVSCSI_REG_OFFSET_KICK_NON_RW_IO:
1014         trace_pvscsi_io_write("PVSCSI_REG_OFFSET_KICK_NON_RW_IO", val);
1015         pvscsi_process_io(s);
1016         break;
1017 
1018     case PVSCSI_REG_OFFSET_KICK_RW_IO:
1019         trace_pvscsi_io_write("PVSCSI_REG_OFFSET_KICK_RW_IO", val);
1020         pvscsi_process_io(s);
1021         break;
1022 
1023     case PVSCSI_REG_OFFSET_DEBUG:
1024         trace_pvscsi_io_write("PVSCSI_REG_OFFSET_DEBUG", val);
1025         break;
1026 
1027     default:
1028         trace_pvscsi_io_write_unknown(addr, size, val);
1029         break;
1030     }
1031 
1032 }
1033 
1034 static uint64_t
1035 pvscsi_io_read(void *opaque, hwaddr addr, unsigned size)
1036 {
1037     PVSCSIState *s = opaque;
1038 
1039     switch (addr) {
1040     case PVSCSI_REG_OFFSET_INTR_STATUS:
1041         trace_pvscsi_io_read("PVSCSI_REG_OFFSET_INTR_STATUS",
1042                              s->reg_interrupt_status);
1043         return s->reg_interrupt_status;
1044 
1045     case PVSCSI_REG_OFFSET_INTR_MASK:
1046         trace_pvscsi_io_read("PVSCSI_REG_OFFSET_INTR_MASK",
1047                              s->reg_interrupt_status);
1048         return s->reg_interrupt_enabled;
1049 
1050     case PVSCSI_REG_OFFSET_COMMAND_STATUS:
1051         trace_pvscsi_io_read("PVSCSI_REG_OFFSET_COMMAND_STATUS",
1052                              s->reg_interrupt_status);
1053         return s->reg_command_status;
1054 
1055     default:
1056         trace_pvscsi_io_read_unknown(addr, size);
1057         return 0;
1058     }
1059 }
1060 
1061 
1062 static void
1063 pvscsi_init_msi(PVSCSIState *s)
1064 {
1065     int res;
1066     PCIDevice *d = PCI_DEVICE(s);
1067 
1068     res = msi_init(d, PVSCSI_MSI_OFFSET(s), PVSCSI_MSIX_NUM_VECTORS,
1069                    PVSCSI_USE_64BIT, PVSCSI_PER_VECTOR_MASK, NULL);
1070     if (res < 0) {
1071         trace_pvscsi_init_msi_fail(res);
1072         s->msi_used = false;
1073     } else {
1074         s->msi_used = true;
1075     }
1076 }
1077 
1078 static void
1079 pvscsi_cleanup_msi(PVSCSIState *s)
1080 {
1081     PCIDevice *d = PCI_DEVICE(s);
1082 
1083     msi_uninit(d);
1084 }
1085 
1086 static const MemoryRegionOps pvscsi_ops = {
1087         .read = pvscsi_io_read,
1088         .write = pvscsi_io_write,
1089         .endianness = DEVICE_LITTLE_ENDIAN,
1090         .impl = {
1091                 .min_access_size = 4,
1092                 .max_access_size = 4,
1093         },
1094 };
1095 
1096 static const struct SCSIBusInfo pvscsi_scsi_info = {
1097         .tcq = true,
1098         .max_target = PVSCSI_MAX_DEVS,
1099         .max_channel = 0,
1100         .max_lun = 0,
1101 
1102         .get_sg_list = pvscsi_get_sg_list,
1103         .complete = pvscsi_command_complete,
1104         .cancel = pvscsi_request_cancelled,
1105 };
1106 
1107 static void
1108 pvscsi_realizefn(PCIDevice *pci_dev, Error **errp)
1109 {
1110     PVSCSIState *s = PVSCSI(pci_dev);
1111 
1112     trace_pvscsi_state("init");
1113 
1114     /* PCI subsystem ID, subsystem vendor ID, revision */
1115     if (PVSCSI_USE_OLD_PCI_CONFIGURATION(s)) {
1116         pci_set_word(pci_dev->config + PCI_SUBSYSTEM_ID, 0x1000);
1117     } else {
1118         pci_set_word(pci_dev->config + PCI_SUBSYSTEM_VENDOR_ID,
1119                      PCI_VENDOR_ID_VMWARE);
1120         pci_set_word(pci_dev->config + PCI_SUBSYSTEM_ID,
1121                      PCI_DEVICE_ID_VMWARE_PVSCSI);
1122         pci_config_set_revision(pci_dev->config, 0x2);
1123     }
1124 
1125     /* PCI latency timer = 255 */
1126     pci_dev->config[PCI_LATENCY_TIMER] = 0xff;
1127 
1128     /* Interrupt pin A */
1129     pci_config_set_interrupt_pin(pci_dev->config, 1);
1130 
1131     memory_region_init_io(&s->io_space, OBJECT(s), &pvscsi_ops, s,
1132                           "pvscsi-io", PVSCSI_MEM_SPACE_SIZE);
1133     pci_register_bar(pci_dev, 0, PCI_BASE_ADDRESS_SPACE_MEMORY, &s->io_space);
1134 
1135     pvscsi_init_msi(s);
1136 
1137     if (pci_is_express(pci_dev) && pci_bus_is_express(pci_get_bus(pci_dev))) {
1138         pcie_endpoint_cap_init(pci_dev, PVSCSI_EXP_EP_OFFSET);
1139     }
1140 
1141     s->completion_worker = qemu_bh_new(pvscsi_process_completion_queue, s);
1142 
1143     scsi_bus_new(&s->bus, sizeof(s->bus), DEVICE(pci_dev),
1144                  &pvscsi_scsi_info, NULL);
1145     /* override default SCSI bus hotplug-handler, with pvscsi's one */
1146     qbus_set_hotplug_handler(BUS(&s->bus), OBJECT(s), &error_abort);
1147     pvscsi_reset_state(s);
1148 }
1149 
1150 static void
1151 pvscsi_uninit(PCIDevice *pci_dev)
1152 {
1153     PVSCSIState *s = PVSCSI(pci_dev);
1154 
1155     trace_pvscsi_state("uninit");
1156     qemu_bh_delete(s->completion_worker);
1157 
1158     pvscsi_cleanup_msi(s);
1159 }
1160 
1161 static void
1162 pvscsi_reset(DeviceState *dev)
1163 {
1164     PCIDevice *d = PCI_DEVICE(dev);
1165     PVSCSIState *s = PVSCSI(d);
1166 
1167     trace_pvscsi_state("reset");
1168     pvscsi_reset_adapter(s);
1169 }
1170 
1171 static int
1172 pvscsi_pre_save(void *opaque)
1173 {
1174     PVSCSIState *s = (PVSCSIState *) opaque;
1175 
1176     trace_pvscsi_state("presave");
1177 
1178     assert(QTAILQ_EMPTY(&s->pending_queue));
1179     assert(QTAILQ_EMPTY(&s->completion_queue));
1180 
1181     return 0;
1182 }
1183 
1184 static int
1185 pvscsi_post_load(void *opaque, int version_id)
1186 {
1187     trace_pvscsi_state("postload");
1188     return 0;
1189 }
1190 
1191 static bool pvscsi_vmstate_need_pcie_device(void *opaque)
1192 {
1193     PVSCSIState *s = PVSCSI(opaque);
1194 
1195     return !(s->compat_flags & PVSCSI_COMPAT_DISABLE_PCIE);
1196 }
1197 
1198 static bool pvscsi_vmstate_test_pci_device(void *opaque, int version_id)
1199 {
1200     return !pvscsi_vmstate_need_pcie_device(opaque);
1201 }
1202 
1203 static const VMStateDescription vmstate_pvscsi_pcie_device = {
1204     .name = "pvscsi/pcie",
1205     .needed = pvscsi_vmstate_need_pcie_device,
1206     .fields = (VMStateField[]) {
1207         VMSTATE_PCI_DEVICE(parent_obj, PVSCSIState),
1208         VMSTATE_END_OF_LIST()
1209     }
1210 };
1211 
1212 static const VMStateDescription vmstate_pvscsi = {
1213     .name = "pvscsi",
1214     .version_id = 0,
1215     .minimum_version_id = 0,
1216     .pre_save = pvscsi_pre_save,
1217     .post_load = pvscsi_post_load,
1218     .fields = (VMStateField[]) {
1219         VMSTATE_STRUCT_TEST(parent_obj, PVSCSIState,
1220                             pvscsi_vmstate_test_pci_device, 0,
1221                             vmstate_pci_device, PCIDevice),
1222         VMSTATE_UINT8(msi_used, PVSCSIState),
1223         VMSTATE_UINT32(resetting, PVSCSIState),
1224         VMSTATE_UINT64(reg_interrupt_status, PVSCSIState),
1225         VMSTATE_UINT64(reg_interrupt_enabled, PVSCSIState),
1226         VMSTATE_UINT64(reg_command_status, PVSCSIState),
1227         VMSTATE_UINT64(curr_cmd, PVSCSIState),
1228         VMSTATE_UINT32(curr_cmd_data_cntr, PVSCSIState),
1229         VMSTATE_UINT32_ARRAY(curr_cmd_data, PVSCSIState,
1230                              ARRAY_SIZE(((PVSCSIState *)NULL)->curr_cmd_data)),
1231         VMSTATE_UINT8(rings_info_valid, PVSCSIState),
1232         VMSTATE_UINT8(msg_ring_info_valid, PVSCSIState),
1233         VMSTATE_UINT8(use_msg, PVSCSIState),
1234 
1235         VMSTATE_UINT64(rings.rs_pa, PVSCSIState),
1236         VMSTATE_UINT32(rings.txr_len_mask, PVSCSIState),
1237         VMSTATE_UINT32(rings.rxr_len_mask, PVSCSIState),
1238         VMSTATE_UINT64_ARRAY(rings.req_ring_pages_pa, PVSCSIState,
1239                              PVSCSI_SETUP_RINGS_MAX_NUM_PAGES),
1240         VMSTATE_UINT64_ARRAY(rings.cmp_ring_pages_pa, PVSCSIState,
1241                              PVSCSI_SETUP_RINGS_MAX_NUM_PAGES),
1242         VMSTATE_UINT64(rings.consumed_ptr, PVSCSIState),
1243         VMSTATE_UINT64(rings.filled_cmp_ptr, PVSCSIState),
1244 
1245         VMSTATE_END_OF_LIST()
1246     },
1247     .subsections = (const VMStateDescription*[]) {
1248         &vmstate_pvscsi_pcie_device,
1249         NULL
1250     }
1251 };
1252 
1253 static Property pvscsi_properties[] = {
1254     DEFINE_PROP_UINT8("use_msg", PVSCSIState, use_msg, 1),
1255     DEFINE_PROP_BIT("x-old-pci-configuration", PVSCSIState, compat_flags,
1256                     PVSCSI_COMPAT_OLD_PCI_CONFIGURATION_BIT, false),
1257     DEFINE_PROP_BIT("x-disable-pcie", PVSCSIState, compat_flags,
1258                     PVSCSI_COMPAT_DISABLE_PCIE_BIT, false),
1259     DEFINE_PROP_END_OF_LIST(),
1260 };
1261 
1262 static void pvscsi_realize(DeviceState *qdev, Error **errp)
1263 {
1264     PVSCSIClass *pvs_c = PVSCSI_DEVICE_GET_CLASS(qdev);
1265     PCIDevice *pci_dev = PCI_DEVICE(qdev);
1266     PVSCSIState *s = PVSCSI(qdev);
1267 
1268     if (!(s->compat_flags & PVSCSI_COMPAT_DISABLE_PCIE)) {
1269         pci_dev->cap_present |= QEMU_PCI_CAP_EXPRESS;
1270     }
1271 
1272     pvs_c->parent_dc_realize(qdev, errp);
1273 }
1274 
1275 static void pvscsi_class_init(ObjectClass *klass, void *data)
1276 {
1277     DeviceClass *dc = DEVICE_CLASS(klass);
1278     PCIDeviceClass *k = PCI_DEVICE_CLASS(klass);
1279     PVSCSIClass *pvs_k = PVSCSI_DEVICE_CLASS(klass);
1280     HotplugHandlerClass *hc = HOTPLUG_HANDLER_CLASS(klass);
1281 
1282     k->realize = pvscsi_realizefn;
1283     k->exit = pvscsi_uninit;
1284     k->vendor_id = PCI_VENDOR_ID_VMWARE;
1285     k->device_id = PCI_DEVICE_ID_VMWARE_PVSCSI;
1286     k->class_id = PCI_CLASS_STORAGE_SCSI;
1287     k->subsystem_id = 0x1000;
1288     device_class_set_parent_realize(dc, pvscsi_realize,
1289                                     &pvs_k->parent_dc_realize);
1290     dc->reset = pvscsi_reset;
1291     dc->vmsd = &vmstate_pvscsi;
1292     dc->props = pvscsi_properties;
1293     set_bit(DEVICE_CATEGORY_STORAGE, dc->categories);
1294     hc->unplug = pvscsi_hot_unplug;
1295     hc->plug = pvscsi_hotplug;
1296 }
1297 
1298 static const TypeInfo pvscsi_info = {
1299     .name          = TYPE_PVSCSI,
1300     .parent        = TYPE_PCI_DEVICE,
1301     .class_size    = sizeof(PVSCSIClass),
1302     .instance_size = sizeof(PVSCSIState),
1303     .class_init    = pvscsi_class_init,
1304     .interfaces = (InterfaceInfo[]) {
1305         { TYPE_HOTPLUG_HANDLER },
1306         { INTERFACE_PCIE_DEVICE },
1307         { INTERFACE_CONVENTIONAL_PCI_DEVICE },
1308         { }
1309     }
1310 };
1311 
1312 static void
1313 pvscsi_register_types(void)
1314 {
1315     type_register_static(&pvscsi_info);
1316 }
1317 
1318 type_init(pvscsi_register_types);
1319